2011-08-19 82 views
14

上下文

我想用相同的圖例在同一頁上繪製兩個ggplot2。 http://code.google.com/p/gridextra/wiki/arrangeGrob敘述,如何做到這一點。這已經很好看了。但是......在我的例子中,我有兩個具有相同x軸和不同y軸的圖。當y軸的範圍至少比另一個繪圖高10倍(例如10000而不是1000)時,ggplot2(或者網格?)不能校正繪圖(見下面的輸出)。將多個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 = "") 

輸出

Example image

+1

參見:http://stackoverflow.com/questions/13294952/left-align-two-g raph-edges-ggplot/13295880#13295880? –

回答

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) 
+3

對於給出的示例,同意切面似乎是更好的選擇。如果OP堅持獨立完成y軸縮放,您還可以添加'scales =「free_y」'。 – joran

+0

謝謝@joran - 不記得該怎麼做。 –

+2

只在輸出的標籤上添加空格。一旦我通過tikzdevice運行它,空間被忽略。 – apepper

10

做同樣的事情更通用的方式,但在一個更清潔的方式是使用格式化ARG:

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

做同樣的你的第二個情節,並確保設置寬度> =你在這兩個地塊預計人數最廣。

+5

在我的ggplot2版本中,參數是「[labels](http://docs.ggplot2.org/current/scale_continuous.html)」,而不是「formatter」。 – simlmx

7

1.使用cowplot包:

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

enter image description here


2.使用tracksggbio包:

注:似乎有一個錯誤,x蜱不對齊。 (在17/03/2016測試,ggbio_1.18。5)

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

enter image description here

0

您的問題在ggbio的解決方法是修復以下列方式將原來的地塊x軸座標:

library(ggbio) 
p1 <- f() 
fixed(p1) <- TRUE 
p2 <- f() 
fixed(p2) <- TRUE 
tracks(p1,p2) 

最佳,

Yatrosin