r - 用不同的 y 尺度覆盖直方图
问题描述
我正在努力解决以下问题:
我想绘制两个直方图,但由于两个类之一的统计数据比另一个少得多,我需要添加第二个 y 轴以允许直接比较值。
我在下面报告我目前使用的代码和结果。
先感谢您!
ggplot(data,aes(x= x ,group=class,fill=class)) + geom_histogram(position="identity",
alpha=0.5, bins = 20)+ theme_bw()
解决方案
考虑以下情况,您有 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()
.
推荐阅读
- web-services - com.sun.xml.messaging.saaj.SOAPExceptionImpl:无效的内容类型:文本/html。这是错误消息而不是 SOAP 响应吗?
- java - 将 JPA 的 SessionFactory 配置到 Spring 中
- javascript - 在 VueJS 中存储图像的正确位置是什么 - 公共文件夹或资产文件夹?
- c# - 依赖注入 .NET Core 2.2 导致的内存泄漏
- javascript - 哭泣。使用 `import()` 后加载块失败
- python - 如何在使用 librosa.display.specshow 创建的图中删除 Y 轴标签、刻度和轴标签
- php - 在 Laravel 中获取用户代理并使用正确的域为用户提供服务
- python - Tkinter 没有注册一些关键事件
- java - 在 nimnus 外观和感觉中显示文本的 netbeans 问题
- mongodb - 使用应用于 MongoDB 中的更改流的聚合阶段从子数组中删除元素?