使用R中的ggplot2将平均值映射到计数图上

时间:2015-06-19 16:58:41

标签: r ggplot2

我的数据框如下:

variable=c("D","D","C","C","C","A","B","B","B","B")
value=c(80,100,70,68,65,45,33,31,36,32)
Count=as.integer(c(5,10,4,5,2,7,3,5,6,2))
mean=c(93.3,93.3,68.2,68.2,68.2,45,33.4,33.4,33.4,33.4)
df=data.frame(variable=variable,value=value,Count=Count,mean=mean)

我可以做一个很好的情节(正方形的大小对应于具有特定x值和y值的观察计数),如下所示:

ggplot(df, aes(variable, value)) + geom_point(aes(size = Count), pch=15) + guides(fill=guide_legend(title="New")) + theme(legend.text=element_text(size=rel(2.3)), legend.title=element_text(size=rel(2.3), face="plain"), legend.position="right", axis.text = element_text(size=rel(2.3)), axis.title = element_text(size = rel(2.3))) + labs(x="Topic", y = "Percentage Grade")

但是,我现在想要在四个主题中添加一个水平条,表示平均百分比等级。这些值存储在df $ mean中。我无法弄清楚如何实现这一目标。我尝试使用geom_line()函数和水平线选项...但这似乎绘制了垂直线!

ggplot(df, aes(variable, value)) + geom_point(aes(size = Count), pch=15) + guides(fill=guide_legend(title="New")) + theme(legend.text=element_text(size=rel(2.3)), legend.title=element_text(size=rel(2.3), face="plain"), legend.position="right", axis.text = element_text(size=rel(2.3)), axis.title = element_text(size = rel(2.3))) + labs(x="Topic", y = "Percentage Grade") + geom_line(stat = "hline", yintercept = df$mean)

谢谢...

1 个答案:

答案 0 :(得分:0)

您可以使用geom_segment

执行此操作
ggplot(df, aes(variable, value)) + 
    geom_point(aes(size = Count), pch=15) +
    geom_segment(aes(x=variable, y=mean-.1, 
                    xend=variable, yend=mean+.1),
                color="red", size=I(40))

enter image description here