我想问一下是否可以用该点所代表的观察值的百分比(即比例)来标记 stat_sum 绘制的每个点。理想情况下,我希望标签采用百分比格式而不是十进制格式。
非常感谢您的宝贵时间。
编辑:最小可重现示例
library("ggplot2")
library("scales")
ggplot(diamonds, aes(x = cut, y = clarity)) +
stat_sum(aes(group = 1)) +
scale_size_continuous(labels=percent)
所以我的问题是,如何(如果可能)用它们的“prop”百分比值标记每个汇总点。
最佳答案
有几个选项。我假设不需要图例,因为这些点标有百分比计数。
一种选择是添加另一个 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))
关于r - ggplot2 stat_sum : Label points with percentage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13418133/