【问题标题】:Overlaying histogram with different y-scales用不同的 y 尺度覆盖直方图
【发布时间】:2020-02-11 12:17:53
【问题描述】:

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

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

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

提前谢谢你!


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

【问题讨论】:

标签: r ggplot2 histogram


【解决方案1】:

考虑以下情况,您有 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)))

您可以使用y = stat(ncount) 将每个组的计数扩展到最多 1:

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() 取代。

【讨论】:

  • 谢谢大师,原来是这样!简单快速,我不知道我是怎么错过的。你帮了我很多。祝你今天过得愉快! =)
【解决方案2】:

如何将它们与方面并排比较?

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

【讨论】:

  • 感谢您的建议。但是,由于我必须为 6 组重复相同的直方图,所以我试图在一张图表中总结这两个直方图。无论如何,如果我无法找到方法,我会听从你的建议。最好的。
猜你喜欢
  • 2017-05-04
  • 2021-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-17
  • 2019-10-06
  • 2011-10-20
相关资源
最近更新 更多