13

I want to make a figure which have reversed y-axis and x-axis at y=0. y axis was reversed with scale_y_reverse, but x-axis stayed at the bottom.

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

I tried the code from this post like in below, but didn't work.

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

I don't need to have two x-axis, simply just move from bottom to the top.

tonytonov
  • 25,060
  • 16
  • 82
  • 98
Megumi
  • 131
  • 1
  • 3
  • 3
    The [feature request](https://github.com/hadley/ggplot2/issues/619) for this is still open. I don't think it has been implemented yet. That means you would have to muck around on the grid level. – Roland Jan 10 '14 at 08:43
  • If it's a one-off, you could consider saving the plot as a vector/PDF and then moving the axis in vector drawing software (e.g. Inkscape). – Alexander Vos de Wael Jan 10 '14 at 19:18
  • Thanks for suggestions, I hope they'll implement this soon. Tentatively I started editing on Inkscape. – Megumi Jan 23 '14 at 17:31
  • Does anyone understand the reasoning behind this feature not being implemented? Is there some philosphy with respect to Grammer of Graphics that shies away from having an x-axis on the top of a plot? – tumultous_rooster Dec 05 '14 at 17:47
  • @Matt O'Brien, there is a reluctance to implement it because it can be mis-used. I don't get it. ``The Economist`` doesn't get it... – PatrickT Dec 15 '14 at 11:58

2 Answers2

4

This is still not possible in ggplot2, but it is possible in ggvis, which combines the ggplot2 grammer with dplyr pipelines. Just use the add_axis function to put the axis at the top.

# 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") 
shadow
  • 21,823
  • 4
  • 63
  • 77
0

You can also use:

library(cowplot)
ggdraw(switch_axis_position(p, axis = 'x'))
Clay
  • 2,584
  • 1
  • 28
  • 63