我试图创建一个直方图,其中计数和相对频率(或比例)数据都显示在y轴上,前者显示在左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
功能不正确。但我不知道还有什么别的办法。如果能提供帮助,我将不胜感激。