How to change positions of x and y axis in ggplot2

前端 未结 2 712
我寻月下人不归
我寻月下人不归 2020-12-01 07:58

In my real research world, it is very common to show x-axis on the top (or both top and bottom) and y-axis on the right. However, the default positions are x on the bottom a

相关标签:
2条回答
  • 2020-12-01 08:33

    From ggplot 2.2.0 you can set the position of the axes with the position argument in scale_:

    ggplot(mpg, aes(displ, hwy)) + 
      geom_point() + 
      scale_x_continuous(position = "top") + 
      scale_y_continuous(position = "right")
    

    0 讨论(0)
  • 2020-12-01 08:40

    ggplot2 solution

    I adopt This solution to create a right y axis. Personally I find manipulating grobs using within a gtable really difficult. I give up with the x-axis but I give a lattice solution. I hope this functionality will be implemented in ggplot2 as soon as possible.

    library(ggplot2)
    library(gtable)
    library(grid)
    grid.newpage()
    dat <- data.frame(x<-seq(0, 10, 0.1),y = sin(x * pi))
    p <- ggplot(dat, aes(x, y)) + geom_line(colour = "blue") + theme_bw()
    # extract gtable
    g <- ggplot_gtable(ggplot_build(p))
    
    # axis tweaks
    ia <- which(g$layout$name == "axis-l")
    ax <- g$grobs[[ia]]$children[[2]]
    ax$widths <- rev(ax$widths)
    ax$grobs <- rev(ax$grobs)
    ax$grobs[[1]]$x <- ax$grobs[[1]]$x - unit(1, "npc") + unit(0.15, "cm")
    pp <- c(subset(g$layout, name == "panel", select = t:r))
    g <- gtable_add_cols(g, g$widths[g$layout[ia, ]$l], length(g$widths) - 1)
    g <-  gtable_add_grob(g, ax, pp$t, length(g$widths) - 1, pp$b)
    g$grobs[[ia]]$children[[2]] <- NULL
    ##############################
    ia <- which(g$layout$name == "ylab")
    ylab <- g$grobs[[ia]]
    g <- gtable_add_cols(g, g$widths[g$layout[ia, ]$l], length(g$widths) - 1)
    g <-  gtable_add_grob(g, ylab, pp$t, length(g$widths) - 1, pp$b)
    g$grobs[[ia]]$label = ''
    grid.draw(g)
    

    enter image description here

    lattice solution

    This is not a ggplot2 solution , but lattice one. Using latticeExtra with a ggplot2 theme we can get a similar look with the desired behavior.

    library(latticeExtra)
    xyplot(y~ x, type='l', scales=list(x=list(alternating=2),
                                       y=list(alternating=2)),
           par.settings = ggplot2like(),axis=axis.grid)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题