如何在此图上绘制误差线并更改叠加?

时间:2013-07-26 18:15:37

标签: r ggplot2

您有这个数据集:

tdat=structure(list(Condition = structure(c(1L, 3L, 2L, 1L, 3L, 2L, 
1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 3L, 2L, 1L, 
3L, 2L, 1L, 3L, 2L), .Label = c("AS", "Dup", "MCH"), class = "factor"), 
    variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 3L, 
    3L, 3L, 3L), .Label = c("Bot", "Top", "All"), class = "factor"), 
    value = c(1.782726022, 1, 2.267946449, 1.095240234, 1, 1.103630141, 
    1.392545278, 1, 0.854984833, 4.5163067, 1, 4.649271897, 0.769428018, 
    1, 0.483117123, 0.363854608, 1, 0.195799358, 0.673186975, 
    1, 1.661568993, 1.174998373, 1, 1.095026419, 1.278455823, 
    1, 0.634152231)), .Names = c("Condition", "variable", "value"
), row.names = c(NA, -27L), class = "data.frame")

> head(tdat)
  Condition variable    value
1        AS      Bot 1.782726
2       MCH      Bot 1.000000
3       Dup      Bot 2.267946
4        AS      Bot 1.095240
5       MCH      Bot 1.000000
6       Dup      Bot 1.103630

我可以使用此代码来绘制它:

ggplot(tdat, aes(x=interaction(Condition,variable,drop=TRUE,sep='-'), y=value,
                 fill=Condition)) + 
                 geom_point() +
                 scale_color_discrete(name='interaction levels')+
        stat_summary(fun.y='mean', geom='bar',
                aes(label=signif(..y..,4),x=as.integer(interaction(Condition,variable))))

http://postimg.org/image/5fwdwuu5t/

我有两个问题:

  1. 如何更改叠加层,以便黑点不被隐藏 条形图(每列应显示3个点)

  2. 如何使用标准在栏顶部添加垂直错误栏     偏离黑点?

2 个答案:

答案 0 :(得分:4)

我不太赞成将误差条与条形图混合。

在ggplot2中,按照将它们添加到绘图中的顺序绘制geoms。因此,为了使点不被隐藏,请在条形后添加它们。

ggplot(tdat, aes(x=interaction(Condition,variable,drop=TRUE,sep='-'), y=value,
                 fill=Condition)) +  
  stat_summary(fun.data="mean_sdl", mult=1, geom="errorbar") +
  stat_summary(fun.y='mean', geom='bar') + 
  geom_point(show_guide=FALSE) +
  scale_fill_discrete(name='interaction levels')

enter image description here

答案 1 :(得分:2)

像这样:

tdat$x <- with(tdat,interaction(Condition,variable,drop=TRUE,sep='-'))
tdat_err <- ddply(tdat,.(x),
                  summarise,ymin = mean(value) - sd(value),
                            ymax = mean(value) + sd(value))

ggplot(tdat, aes(x=x, y=value)) + 
        stat_summary(fun.y='mean', geom='bar',
                aes(label=signif(..y..,4),fill=Condition)) + 
        geom_point() + 
        geom_errorbar(data = tdat_err,aes(x = x,ymin = ymin,ymax = ymax,y = NULL),width = 0.5) +
        labs(fill = 'Interaction Levels')

enter image description here

我在某种程度上清理了你的代码。如果在ggplot()调用之外移动任何无关的计算,则会遇到更少的问题。最好先创建新的x变量。一切都更具可读性。

重叠问题只需要重新排序图层。

请注意,在映射scale_colour_*而不是fill时,您使用的是colour(这是一个非常常见的错误)。

唯一的另一个“技巧”是y的取消映射。通常情况下,当事情变得棘手时,我会从顶级aes调用中省略ggplot,以确保每一层都只获得所需的美学。

错误栏我倾向于首先在ggplot之外创建数据框。我发现它更清洁,更容易阅读。

相关问题