我正在尝试创建一个直方图,同时在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
函数中使用的转换函数不正确。但是我不知道有其他方法可以做到这一点。将不胜感激提供的任何帮助。
答案 0 :(得分:1)
由于每个小节的高度都将除以相同的数字,因此您可以预先计算分母(下面的tot_obs
),然后在trans
函数中调用该标量:
library(ggplot2)
library(scales)
# data
df <- datasets::ToothGrowth
# scalar for denominator
tot_obs <- nrow(df)
ggplot(data = df, mapping = aes(x = len)) +
geom_histogram() +
scale_y_continuous(
sec.axis = sec_axis(trans = ~./tot_obs, labels = percent,
name = "proportion (in %)")) +
ylab("count") +
guides(fill = FALSE)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
由reprex package(v0.2.0)于2018-08-16创建。