【发布时间】:2018-08-16 22:09:28
【问题描述】:
我正在尝试创建一个直方图,其中在 y 轴上显示计数和相对频率(或比例)数据,前者在左侧 y 轴上,后者在右侧。 我已经设法创建了基本图,但我得到的百分比值不正确。
# loading necessary libraries
library(ggplot2)
library(scales)
# attempt to display both counts and proportions
ggplot2::ggplot(
data = datasets::ToothGrowth,
mapping = ggplot2::aes(x = len)
) +
ggplot2::stat_bin(
col = "black",
alpha = 0.7,
na.rm = TRUE,
mapping = ggplot2::aes(
y = ..count..
)
) +
ggplot2::scale_y_continuous(
sec.axis = ggplot2::sec_axis(trans = ~ (.)/sum(.),
labels = scales::percent,
name = "proportion (in %)")
) +
ggplot2::ylab("count") +
ggplot2::guides(fill = FALSE)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
如果您创建另一个仅显示比例数据的直方图,这一点就很清楚了。
# just displaying proportion
ggplot2::ggplot(
data = datasets::ToothGrowth,
mapping = ggplot2::aes(x = len)
) +
ggplot2::stat_bin(
col = "black",
alpha = 0.7,
na.rm = TRUE,
mapping = ggplot2::aes(
y = ..count.. / sum(..count..)
)
) +
ggplot2::scale_y_continuous(labels = scales::percent) +
ggplot2::ylab("proportion (in %)") +
ggplot2::guides(fill = FALSE)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
我的猜测是我在sec_axis 函数中使用的转换函数不正确。但我不知道有任何其他方法可以做到这一点。将不胜感激提供的任何帮助。
【问题讨论】:
标签: r ggplot2 histogram tidyverse