我想从相同的数据中绘制两个或多个直方图,但反转一组的坐标,如下所示:
(注:此图取自Grossman et al 2011, A composite of Multiple Signals Distinguishes Causal Variants in Regions of Positive Selection)
例如,让我们从 ggplot2 中获取 diamonds 数据集:
> 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
我尝试过的一种方法是使用 stat_bin 计算直方图而不绘制它,更改它返回的计数列的值。
> my_sb <-stat_bin(data=diamonds, mapping=aes(x=x)
stat_bin 的文档说这个函数应该返回一个等于映射的data.frame,但添加四个新列(count、density、ncount、ndensity)。但是,我在任何地方都找不到这些列:
# 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
另一种可能的方法是使用 scale_y_reverse(),但我不知道如何将其应用于单个数据集。
我能想到的第三种方法是使用 viewPorts,但我不太确定如何实现它。
最佳答案
可能像这样:
ggplot(data = diamonds) +
geom_histogram(aes(x = x,y = ..count..)) +
geom_histogram(aes(x = x,y = -..count..))
仅供引用 - 我不记得我过去是如何做到这一点的,所以我在 Google 上搜索了“ggplot2 倒置直方图”并点击了 first hit。 ,一个 StackOverflow 问题。
我不确定
stat_bin
的 proto 对象到底是怎样的。返回是结构化的,但新变量在某处。其工作方式是 geom_histogram
本身调用 stat_bin
执行分箱,因此它可以访问计算变量,我们可以将其映射到 y
多变的。
关于r - ggplot2:在同一页面中绘制多个直方图,但一个具有倒置坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17188067/