使用 ggplot2 在直方图中显示百分比而不是计数 | 电阻

Lam*_*aMo 6 r histogram ggplot2

我正在使用直方图来绘制我的 3 组数据。但正如直方图所做的那样,它计算每个组有多少这些值(在 x 轴上),我想要的是这个值出现/出现的百分比(以 % 为单位)。

这是我生成的图,我使用此常规代码绘制直方图:

ggplot2.histogram(data=dat, xName='dens',
                  groupName='lines', legendPosition="top",
                  alpha=0.1) + 
  labs(x="X", y="Count") +
  theme(panel.border = element_rect(colour = "black"),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black")) + 
  theme_bw()+
  theme(legend.title=element_blank())
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

任何想法/建议?

Moo*_*per 4

我们可以用计算统计量的相对值替换 y 美学count,并设置比例来显示百分比:

ggplot2.histogram(data=dat, xName='dens',
                  groupName='lines', legendPosition="top",
                  alpha=0.1) + 
  labs(x="X", y="Count") +
  theme(panel.border = element_rect(colour = "black"),
        panel.grid.minor = element_blank(), 
        axis.line = element_line(colour = "black")) + 
  theme_bw()+
  theme(legend.title=element_blank()) + 
  aes(y = after_stat(count)/sum(after_stat(count))) + 
  scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)