Kat*_*teA 4 r histogram ggplot2
我用百分比做了一个直方图(效果很好),但是当我尝试打印百分比值时,y 轴的刻度不再正确。
百分比直方图的代码(效果很好)如下:
data_impact_final %>%
ggplot(aes(x = time_to_treat_month)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),binwidth=6) +
scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用 stat_bin 打印图表上的百分比时,y 轴的刻度不再正确。这是我用来打印百分比的代码:
data_impact_final %>%
ggplot(aes(x = time_to_treat_month)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),binwidth=6) +
stat_bin(binwidth=6, geom='text', color='white', aes(label = scales::percent((..count..)/sum(..count..))),position=position_stack(vjust = 0.5))+
scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)
感谢您的帮助
问题是标签放置在y=..count..。为了解决您的问题,也y=..count../sum(..count..)使用stat_bin。
更新ggplot2 3.4.0自点点符号 ( )起,..count..已弃用,取而代之的是after_stat()。
使用ggplot2::mpg示例数据:
library(ggplot2)
library(dplyr)
mpg %>%
ggplot(aes(x = hwy)) +
geom_histogram(aes(y = after_stat(count / sum(count))),binwidth=6) +
scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)

ggplot(mpg, aes(x = hwy)) +
geom_histogram(aes(y = after_stat(count / sum(count))), binwidth = 6) +
stat_bin(
binwidth = 6, geom = "text", color = "white",
aes(y = after_stat(count / sum(count)),
label = scales::percent(after_stat(count / sum(count)))),
position = position_stack(vjust = 0.5)
) +
scale_y_continuous(labels = scales::percent)
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
7092 次 |
| 最近记录: |