【发布时间】:2019-12-05 09:24:22
【问题描述】:
我想在同一个图上绘制直方图和密度。我想在下面添加的是自定义 y 轴标签,类似于 sprintf("[%s] %s", ..density.., ..count..) - 一个刻度值处的两个数字。是否有可能通过scale_y_continuous 获得这个,或者我需要以某种方式解决这个问题?
低于使用scales::trans_new 和sec_axis 的当前进度。 sec_axis 是可以接受的,但最理想的输出如下图所示。
set.seed(1)
var <- rnorm(4000)
binwidth <- 2 * IQR(var) / length(var) ^ (1 / 3)
count_and_proportion_label <- function(x) {
sprintf("%s [%.2f%%]", x, x/sum(x) * 100)
}
ggplot(data = data.frame(var = var), aes(x = var, y = ..count..)) +
geom_histogram(binwidth = binwidth) +
geom_density(aes(y = ..count.. * binwidth)) +
scale_y_continuous(
# this way
trans = trans_new(name = "count_and_proportion",
format = count_and_proportion_label,
transform = function(x) x,
inverse = function(x) x),
# or this way
sec.axis = sec_axis(trans = ~./sum(.),
labels = percent,
name = "proportion (in %)")
)
在基于graphics::hist 输出之前,我尝试创建带有中断的对象 - 但这两个直方图不同。
bins <- (max(var) - min(var))/binwidth
hdata <- hist(var, breaks = bins, right = FALSE)
# hist generates different bins than `ggplot2`
最后我想得到这样的东西:
【问题讨论】: