2014-01-10 109 views
12

我想使已反轉y軸和x軸爲y = 0的圖。 Y軸用scale_y_reverse逆轉,但x軸留在底部。GGPLOT2移動x軸到頂部(在0使用反轉Y軸相交)

p <- ggplot(df, aes(x= conc, y=depth, group=factor(stn), color=factor(stn)))+ 
geom_point(shape=1)+ 
geom_path(alpha=0.5)+ 
scale_y_reverse(limits=(c(20,0)), expand=c(0,0))+ 
scale_x_continuous(expand=c(0,0)) 

我嘗試了下面的this post的代碼,但沒有奏效。

p + 
scale_x_continuous(guide = guide_axis(position = "top")) + 
scale_y_continuous(guide = guide_axis(position = "right")) 

我不需要有兩個x軸,只需從底部移動到頂部即可。

+3

[功能要求(https://github.com/hadley/ggplot2/issues/619)這仍然是開放的。我認爲它還沒有實施。這意味着你將不得不在網格層面進行調整。 – Roland

+0

如果它是一個一次性的,你可以考慮保存的情節作爲載體/ PDF,然後在矢量繪圖軟件(如Inkscape中)移動軸。 –

+0

感謝您的建議,希望他們能儘快實施。暫時我開始在Inkscape上編輯。 – Megumi

回答

3

這仍然不可能在ggplot2,但它可能在ggvis,它結合了ggplot2文法和dplyr管道。只需使用add_axis函數把軸頂部。

# sample data 
N <- 20 
df <- data.frame(conc = seq(0, N), 
       depth = runif(N+1, 0, 20), 
       stn = rep(1:4, length=N+1)) 
# ggplot version 
require(ggplot2) 
p <- ggplot(df, aes(x= conc, y=depth, group=factor(stn), color=factor(stn)))+ 
    geom_point(shape=1)+ 
    geom_path(alpha=0.5)+ 
    scale_y_reverse(limits=(c(20,0)), expand=c(0,0))+ 
    scale_x_continuous(expand=c(0,0)) 
p 
# ggvis version 
require(ggvis) 
df %>% transform(stn = factor(stn)) %>% 
    ggvis(x = ~conc, y = ~depth, stroke = ~stn) %>% 
    layer_points(shape := "circle", fill := "white") %>% 
    layer_lines(opacity := 0.5) %>% 
    scale_numeric("y", reverse=TRUE, domain=c(0,20), expand=c(0,0)) %>% 
    scale_numeric("x", expand=c(0,0)) %>% 
    add_axis("x", orient = "top") 
0

您還可以使用:

library(cowplot) 
ggdraw(switch_axis_position(p, axis = 'x'))