2012-11-16 95 views
3

我想问一下,是否可以用stat_sum绘制的每个点与该点表示的观察值的百分比(即比例)进行标记。理想情况下,我希望标签采用百分比格式而不是小数。ggplot2 stat_sum:使用百分比标记点

非常感谢您的时间。

编辑:最小的可重复的例子

library("ggplot2") 
library("scales") 

ggplot(diamonds, aes(x = cut, y = clarity)) + 
    stat_sum(aes(group = 1)) + 
    scale_size_continuous(labels=percent) 

Image of the resulting plot

所以我的问题是,如何(如果可能)标记每个与他们的“托”百分比值的汇总点。

+0

也许你可以给一些(可重复)示例代码? – ROLO

+0

道歉,我无法分享我正在使用的数据,但是我生成的情节与文档中的完全相同:http://docs.ggplot2.org/current/stat_sum.html。第二个示例图代表我拥有的。我希望能够使用它们的prop值来标记每个汇总点,尽管理想情况下是以百分比格式。我希望这有助于阐述。 – Harry

+1

@Harry你的问题一直没有答案16个小时,虽然它应该很容易解决,可能是因为你没有提供一个最小可重现的例子。我可以建议你制作一些伪造的数据(一小套)和必要的支持代码的最低限度,然后将它们添加到你的问题。作为另一个新手把它从我身上拿走,这会提高你获得答案的机会。请参阅http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – SlowLearner

回答

9

有几个选项。我会假设这个图例是不需要的,因为这些点是用百分比计数标记的。

一种选择是添加另一个stat_sum()函数,其中包含标签审美和“文本”几何。例如:

library("ggplot2") 

ggplot(diamonds, aes(x = cut, y = clarity, group = 1)) + 
    stat_sum(geom = "point", show.legend = FALSE) + 
    stat_sum(aes(label = paste(round(..prop.. * 100, 2), "%", sep = "")), 
       size = 3, hjust = -0.4, geom = "text", show.legend = FALSE) 

或者,可能不需要这些点。标签可以做所有的工作 - 显示位置和大小:

ggplot(diamonds, aes(x = cut, y = clarity, group = 1)) + 
    stat_sum(aes(label = paste(round(..prop.. * 100, 2), "%", sep = "")), 
       geom = "text", show.legend = FALSE) + 
    scale_size(range=c(2, 8)) 

有时它是更容易地创建外ggplot的汇总表:

library(plyr) 
df = transform(ddply(diamonds, .(cut, clarity), "nrow"), 
     percent = round(nrow/sum(nrow)*100, 2)) 

ggplot(df, aes(x = cut, y = clarity)) + 
    geom_text(aes(size = percent, label = paste(percent, "%", sep = "")), 
        show.legend = FALSE) + 
    scale_size(range = c(2, 8)) 

enter image description here

+0

多么美妙的答案;非常感谢。 – Harry