ggplot2 stat_sum:带百分比的标签点

Har*_*rry 3 r labels ggplot2

我想问一下,是否可以将stat_sum绘制的每个点标记为该点所代表的观察的百分比(即比例).理想情况下,我希望标签是百分比格式而不是十进制格式.

非常感谢你的时间.

编辑:最小可重复的示例

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

ggplot(diamonds, aes(x = cut, y = clarity)) +
  stat_sum(aes(group = 1)) +
  scale_size_continuous(labels=percent)
Run Code Online (Sandbox Code Playgroud)

结果图的图像

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

San*_*att 10

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

一种选择是添加另一个stat_sum()包含标签美学和"文本"geom的功能.例如:

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)
Run Code Online (Sandbox Code Playgroud)

或者,可能不需要积分.标签可以完成所有工作 - 显示位置和大小:

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))
Run Code Online (Sandbox Code Playgroud)

有时在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))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述