Remove blank lines from x axis in ggplot2

后端 未结 2 460
[愿得一人]
[愿得一人] 2021-01-15 00:26

I have a some trouble about removing the space in between x axis values. I want to remove the gap between two values in each facet_wrap

I checked this

2条回答
  •  执笔经年
    2021-01-15 00:41

    I had a similar thought to @alistaire but couldn't get ggplot to relinquish enough control, so I went with cowplot::plot_grid().

    I rearranged the factors by creating the order manually, with B appearing before A.

    df$facet_order <- factor(paste0(df$direc,df$add), levels=c("B1", "A1", "B2", "A2", "B3", "A3", "B4", "A4"))
    

    Creating the plots for A and B individually, then combining them using plot_grid;

    g1 <- ggplot(data=df[df$direc=="B",], aes(x=x, y=yy)) +
      geom_point(size=5, col="red") +
      geom_line(size=1.3, col="red") +
      scale_y_log10(limits=c(1e-8,10), breaks = c(3e-7,1e-3,1e-1,1)) +
      scale_x_continuous(expand = c(0, 0),breaks=c(seq(-40,40,10))) +
      facet_wrap(~facet_order, ncol=1) +
      coord_cartesian(xlim=c(-50,0)) + theme(axis.line.x=element_line(colour="red", size=1.5),
                                             legend.position="none")
    g2 <- ggplot(data=df[df$direc=="A",], aes(x=x, y=yy)) +
      geom_point(size=5, col="blue") +
      geom_line(size=1.3, col="blue") +
      scale_y_log10(limits=c(1e-8,10), breaks = c(3e-7,1e-3,1e-1,1)) +
      scale_x_continuous(expand = c(0, 0),breaks=c(seq(-40,40,10))) +
      facet_wrap(~facet_order, ncol=1) +
      coord_cartesian(xlim=c(0,50)) + theme(axis.text.y=element_blank(),
                                            axis.line.y=element_blank(),
                                            axis.ticks.y=element_blank(),
                                            axis.title.y=element_blank(), 
                                            axis.line.x=element_line(colour="blue", size=1.5),
                                            legend.position="none")
    library(cowplot)
    g <- plot_grid(g1,g2,scale=1.05)
    g
    

    Depending on the output size you're after, you can mess with the size argument to plot_grid and have the x=0 label exactly overlap so that the data line up perfectly.

    My suggestion (in the absence of simply not doing this) would be to do this for all the values of add so that you can manually move the relative x axes so that there is no gap for any of them.

提交回复
热议问题