2014-02-17 59 views
1

我尝试用每个图形的平均比以纪念我的图表标注方式:GGPLOT2在几个图

ggplot(diamonds, aes(x = carat, fill=cut)) + 
stat_density(aes(ymax = ..density.., ymin = -..density..), 
    geom = "ribbon", position = "identity") + 
    facet_grid(. ~ cut) + 
    xlim(0,2.5) + 
    geom_text(data = NULL, x = 0.6, y = 0, label = mean(carat), size=5) + 
    coord_flip() 

例如,在这里,我想“广交会”的曲线图显示的“大路货“,”好“的显示平均值为”良好“等。

另外,但是这是一个额外的,我想如果平均值为1.0,则定位为x,而平均值显示在x = 1.0时

回答

1

有很多方法可以获得标签(和l的位置abels)。在这里,dplyr包用于总结diamonds数据帧;即获得所需的手段。另请注意,标签的格式是两位小数。在下面的代码中,diamonds2数据帧包含手段和标签,用于拨打geom_text

library(ggplot2) 
library(dplyr) 

diamonds2 = transform(summarise(group_by(diamonds, cut), label = mean(carat)), 
    Label = sprintf("%.02f", label)) 

ggplot(diamonds, aes(x = carat, fill=cut)) + 
stat_density(aes(ymax = ..density.., ymin = -..density..), 
    geom = "ribbon", position = "identity") + 
facet_grid(. ~ cut) + 
xlim(0, 2.5) + 
geom_text(data = diamonds2, aes(label = Label, x = label, y = 0), size=5) + 
coord_flip() 

enter image description here

+0

'警告在install.packages:包 'dplyr' 不可用(对于R版本2.15.1)',我不能更换的R工作室的版本(在线服务器服务) – Muramasa

+1

从plyr包中尝试'ddply':'library(plyr); diamonds2 = transform(ddply(diamonds,。(cut),summarize,label = mean(carat)),Label = sprintf(“%。02f”,label))'否则查看'?aggregate'或'?by'。 2.15.1 - 将近2岁。 –

+0

我已经按照你的推荐,但如果我建立这个图,它可能会看到'geom_text'中的平均值和'geom_boxplot'中的平均值的差异,我不知道如何解释它... http:///snag.gy/xtbSs.jpg – Muramasa