14

语境

我想在具有相同图例的同一页面上绘制两个 ggplot2。http://code.google.com/p/gridextra/wiki/arrangeGrob描述了如何做到这一点。这已经看起来不错了。但是...在我的示例中,我有两个具有相同 x 轴和不同 y 轴的图。当 y 轴的范围至少是其他图的 10 倍(例如 10000 而不是 1000)时,ggplot2(或网格?)不会正确对齐图(请参阅下面的输出)。

问题

如何使用两个不同的 y 轴对齐绘图的左侧?

示例代码

x = c(1, 2)
y = c(10, 1000)
data1 = data.frame(x,y)
p1 <- ggplot(data1) + aes(x=x, y=y, colour=x) + geom_line()

y = c(10, 10000)
data2 = data.frame(x,y)
p2 <- ggplot(data2) + aes(x=x, y=y, colour=x) + geom_line()


# Source: http://code.google.com/p/gridextra/wiki/arrangeGrob
leg <- ggplotGrob(p1 + opts(keep="legend_box"))
legend=gTree(children=gList(leg), cl="legendGrob")
widthDetails.legendGrob <- function(x) unit(3, "cm")
grid.arrange(
  p1 + opts(legend.position="none"),
  p2 + opts(legend.position="none"),
  legend=legend, main ="", left = "")

输出

示例图片

4

3 回答 3

10

一种更简洁但更通用的方法是使用格式化程序 arg:

p1 <- ggplot(data1) +
    aes(x=x, y=y, colour=x) +
    geom_line() + 
    scale_y_continuous(formatter = function(x) format(x, width = 5))

对第二个绘图执行相同操作,并确保将宽度设置为 >= 您期望在两个绘图中的最宽数字。

于 2012-09-15T11:30:10.253 回答
8

1.使用cowplot包:

library(cowplot)
plot_grid(p1, p2, ncol=1, align="v")

在此处输入图像描述


2.使用tracksggbio

注意:似乎有一个错误,x 刻度不对齐。(测试于 2016 年 3 月 17 日,ggbio_1.18.5)

library(ggbio)
tracks(data1=p1,data2=p2)

在此处输入图像描述

于 2014-08-22T15:57:19.297 回答
7

如果您不介意无耻的拼凑,只需在 中最长的标签上添加一个额外的字符p1,如下所示:

p1 <- ggplot(data1) +
    aes(x=x, y=y, colour=x) +
    geom_line() + 
    scale_y_continuous(breaks = seq(200, 1000, 200),
                       labels = c(seq(200, 800, 200), " 1000"))

我有两个潜在的问题,如果你有你的理由,我希望你能原谅:

1) 为什么不在两者上使用相同的 y 轴?我觉得这是一种更直接的方法,并且在您上面的示例中通过添加scale_y_continuous(limits = c(0, 10000))p1.

2)这里提供的功能facet_wrap不够吗?很难知道你的数据结构实际上是什么样的,但这里有一个我如何做到这一点的玩具示例:

library(ggplot2)

# Maybe your dataset is like this
x <- data.frame(x = c(1, 2),
                y1 = c(0, 1000),
                y2 = c(0, 10000))

# Molten data makes a lot of things easier in ggplot
x.melt <- melt(x, id.var = "x", measure.var = c("y1", "y2"))

# Plot it - one page, two facets, identical axes (though you could change them),
# one legend
ggplot(x.melt, aes(x = x, y = value, color = x)) +
    geom_line() +
    facet_wrap( ~ variable, nrow = 2)
于 2011-08-19T18:22:45.577 回答