3

我想从相同的数据中绘制两个或多个直方图,但反转一组的坐标,如下所示:

在此处输入图像描述

(注:此图取自Grossman 等人 2011 年的 A composition 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,但我不太确定如何实现它。

4

1 回答 1

4

可能像这样:

ggplot(data = diamonds) + 
    geom_histogram(aes(x = x,y = ..count..)) + 
    geom_histogram(aes(x = x,y = -..count..))

仅供参考 - 我不记得我过去是如何做到这一点的,所以我用谷歌搜索了“ggplot2倒置直方图”并点击了第一个点击,一个 StackOverflow 问题。

我不确定stat_bin返回的 proto 对象的确切结构,但新变量就在某处。它的工作方式是它geom_histogram本身调用stat_bin执行分箱,因此它可以访问计算变量,我们可以将其映射到y变量。

于 2013-06-19T14:14:23.347 回答