r - ggplot2 stat_sum : Label points with percentage

标签 r ggplot2 label

我想问一下是否可以用该点所代表的观察值的百分比(即比例)来标记 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”百分比值标记每个汇总点。

最佳答案

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

一种选择是添加另一个 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

关于r - ggplot2 stat_sum : Label points with percentage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13418133/

相关文章:

Python (tkinter) 入口变量

javascript - 如何正确旋转 D3 旭日图中的文本标签

R - 提高采样功能速度

r - R 上的 ggplot 问题 : code is correct but I keep receiving the error "Must request at least one color from a hue palette"

R 指数产生 NaN

r - 具有较小点的 ggplot 尺寸美学

r - 无法更改 ggplot 中的 ylab

r - 将 BED 文件转换为 WIG 文件

r - 图例中的 ggplot2 虚线未正确显示

iphone - 如何从iOS中的另一个类调用方法?