ggplot2 stat_sum:带百分比的标签点

时间:2012-11-16 14:02:48

标签: r ggplot2 labels

我想问一下,是否可以用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

所以我的问题是,如何(如果可能的话)用'prop'百分比值标记每个汇总点。

1 个答案:

答案 0 :(得分:10)

有几个选择。我假设不需要图例,因为这些点标有百分比计数。

一个选项是添加另一个包含标签美学和“文本”geom的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