r - 在 ggplot 直方图中显示百分比
问题描述
我做了一个百分比直方图(效果很好),但是当我尝试打印百分比的值时,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)
但是,当我尝试使用 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)
谢谢您的帮助
解决方案
问题是标签放置在y=..count..
. 为了解决您的问题y=..count../sum(..count..)
,stat_bin
也可以使用。
使用ggplot2::mpg
示例数据:
library(ggplot2)
library(dplyr)
mpg %>%
ggplot(aes(x = hwy)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),binwidth=6) +
scale_y_continuous(labels = scales::percent)
mpg %>%
ggplot(aes(x = hwy)) +
geom_histogram(aes(y = (..count..)/sum(..count..)),binwidth=6) +
stat_bin(binwidth=6, geom='text', color='white', aes(y = ..count../sum(..count..), label = scales::percent((..count..)/sum(..count..))),position=position_stack(vjust = 0.5))+
scale_y_continuous(labels = scales::percent)
推荐阅读
- javascript - Javascript 正则表达式:第二次出现块:ABC.js 音乐符号
- r - Mac R 与 mdbtools 一起使用 macport install 而不是 home-brew install
- javascript - 在点击按钮之前验证并确保开始年份始终小于结束年份
- python - 当 2 个用户同时使用 bot 时,Telegram bot 中的值混合在一起
- git - 不确定我是否正确地将我的 SHA256 代码正确添加到了 GitHub;终端给出了奇怪的读数
- python - 将十进制小时、DOY 和年份转换为日期时间
- html - 如何在横幅图像上应用白色叠加层
- dart - 将指数数字转换为数字 Dart
- javascript - fabric.Image.filters.Blend 不是构造函数
- reactjs - React 不会让我以完全合理的方式使用 `useEffect`