2015-10-16 163 views
1

我已经使用errbar在R中产生一个显示平均值和标准偏差的数字。绘制两组平均值和标准偏差(使用errbar)

这是我的代码

errbar(data$Type, data$Mean,data$Mean+data$Std,data$Mean-data$Std, 
     xlab="Type",ylab="Score", ylim=c(0,10)) 

其中(水平)产生平均值和STD的一个情节:

我想以产生用于每个“类型”的图,其中(类)存在是不止一个平均值/ std显示在剧情上。所以,我想会是这个样子(或对每个类型的多个数据点)剧情:

this

我可以使用errbar功能来做到这一点?如果不是,你会如何建议在R中这样做?

这里是从dput输出(数据):

structure(list(Type = structure(c(8L, 5L, 7L, 2L, 1L, 6L, 3L, 4L), 
      .Label = c("A", "B", "C", "D", "E", "G", "H", "R"), 
      class = "factor"), Mean = c(5.26785714285714, 5.41071428571429, 5.92857142857143, 
       6.23333333333333, 6.3, 7.78571428571429, 8.38333333333333, 8.75), 
      Std = c(2.3441094046778, 1.80971508291186, 1.50457178749844, 1.86716617466403, 1.93233759251032, 
       1.3931740974961, 1.06848802832164, 1.00445436503037)), 
      .Names = c("Type", "Mean", "Std"), 
      row.names = c(8L, 5L, 7L, 2L, 1L, 6L, 3L, 4L), class = "data.frame") 

回答

0

这里的一个ggplot2方法。首先,添加以下到您发布的数据帧:由Mean

订单数据帧,然后依次通过转换为一个因素锁定:

data = data[order(data$Mean),] 
data$Type = factor(data$Type, levels=data$Type) 

两个行添加到数据帧,使我们就可以绘制一个以上的平均/ errorbar每个Type

data = rbind(data, data.frame(Type=c("R","E"), Mean=c(0.5,1.2), Std=c(1.4,1.7))) 

添加分组变量,使之易于绘制多个值对于给定的Type用不同的颜色:

data$group = c(rep("Group 1",8), rep("Group 2", 2)) 

现在的情节:

ggplot(data, aes(x=Type, Mean, colour=group)) + 
    geom_errorbar(aes(ymax=Mean+Std, ymin=Mean-Std), width=0) + 
    geom_point(size=3) + 
    coord_flip() + 
    theme_grey(base_size=15) + 
    guides(colour=FALSE) 

enter image description here

通过使用分组变量的,你也可以“闪避”点的位置中的给定Type,这可能是有用的如果误差条对于给定值Type重叠。例如:

# Add another row to the data 
data = rbind(data, data.frame(Type="G", Mean=7.5, Std=1.5, group="Group 2")) 

# Dodging function 
pd = position_dodge(width=0.5) 

ggplot(data, aes(x=Type, Mean, colour=group)) + 
    geom_errorbar(aes(ymax=Mean+Std, ymin=Mean-Std), width=0, position=pd) + 
    geom_point(size=3, position=pd) + 
    coord_flip() + 
    theme_grey(base_size=15) + 
    guides(colour=FALSE) 

enter image description here

+0

谢谢 - 真正帮助。 – lily23

+0

我还可以问,有没有人知道如何强迫这种情节的轴在0到10之间?我尝试了一些东西,例如ylim = c(0,10),但没有成功。 – lily23

+0

添加'scale_y_continuous(限制= c(0,10))'。请注意,如果任何数据超出这些限制,ggplot2将会排除它(带有警告)。要设置小于数据范围的限制而不排除任何数据,请使用'coord_cartesian(ylim = c(0,10))'。 – eipi10

相关问题