首页 > 解决方案 > 用不同的 y 尺度覆盖直方图

问题描述

我正在努力解决以下问题:

我想绘制两个直方图,但由于两个类之一的统计数据比另一个少得多,我需要添加第二个 y 轴以允许直接比较值。

我在下面报告我目前使用的代码和结果。

先感谢您!


ggplot(data,aes(x= x ,group=class,fill=class)) + geom_histogram(position="identity",
  alpha=0.5, bins = 20)+ theme_bw() 

阴谋

标签: rggplot2histogram

解决方案


考虑以下情况,您有 800 个与 200 个观察值:

library(ggplot2)

df <- data.frame(
  x = rnorm(1000, rep(c(1, 2), c(800, 200))),
  class = rep(c("A", "B"), c(800, 200))
)

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
  # Note that y = stat(count) is the default behaviour
                 mapping = aes(y = stat(count)))

在此处输入图像描述

您可以使用以下方法将每个组的计数缩放到最大 1 y = stat(ncount)

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
                 mapping = aes(y = stat(ncount)))

在此处输入图像描述

或者,您可以设置y = stat(density)将总面积积分为 1。

ggplot(df, aes(x, fill = class)) +
  geom_histogram(bins = 20, position = "identity", alpha = 0.5,
                 mapping = aes(y = stat(density)))

在此处输入图像描述

请注意,在 ggplot 3.3.0 之后stat()可能会被after_stat().


推荐阅读