dal*_*ogm 4 r histogram ggplot2
我想根据相同的数据绘制两个或多个直方图,但反转一组的坐标,如下所示:

例如,我们从 ggplot2 中获取钻石数据集:
> library(ggplot2)
> head(diamonds)
carat cut color clarity depth table price x y z
1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63
5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
Run Code Online (Sandbox Code Playgroud)
我尝试过的一种方法是使用 stat_bin 计算直方图而不绘制它,更改它返回的计数列的值。
> my_sb <-stat_bin(data=diamonds, mapping=aes(x=x)
Run Code Online (Sandbox Code Playgroud)
stat_bin 的文档说这个函数应该返回一个与映射的 data.frame 相等的 data.frame,但添加四个新列(count、density、ncount、ndenth)。但是,我在任何地方都找不到这些列:
# I supposed that this should contain a count, density columns, but it does not.
> print(head(my_sb$data))
carat cut color clarity depth table price x y z
1 0.23 Ideal E SI2 61.5 55 326 3.95 3.98 2.43
2 0.21 Premium E SI1 59.8 61 326 3.89 3.84 2.31
3 0.23 Good E VS1 56.9 65 327 4.05 4.07 2.31
4 0.29 Premium I VS2 62.4 58 334 4.20 4.23 2.63
5 0.31 Good J SI2 63.3 58 335 4.34 4.35 2.75
6 0.24 Very Good J VVS2 62.8 57 336 3.94 3.96 2.48
Run Code Online (Sandbox Code Playgroud)
另一种可能的方法是使用scale_y_reverse(),但我不知道如何将其应用于单个数据集。
我能想到的第三种方法是使用 viewPorts,但我不太确定如何实现它。
也许像这样:
ggplot(data = diamonds) +
geom_histogram(aes(x = x,y = ..count..)) +
geom_histogram(aes(x = x,y = -..count..))
Run Code Online (Sandbox Code Playgroud)
仅供参考 - 我记不清过去是如何做到这一点的,所以我在 Google 上搜索了“ggplot2 倒置直方图”,然后点击了第一个命中,这是一个 StackOverflow 问题。
我不确定stat_bin返回的原始对象的结构如何,但新变量位于某处。它的工作方式是它geom_histogram本身调用stat_bin来执行分箱,因此它可以访问计算变量,我们可以将其映射到变量y。