简体   繁体   中英

How to make y-axis labels overlap for ggplot figures in R

The y-axis for both figures below are the same (ie, mpg ) and have the same scale. I would like the figure on the left to overlap the y-axis of the figure on the right such that you can only see the tick marks of the y-axis for the figure on the right.

The code below makes both figures and aligns them however you can still see the y-axis labels for the figure on the right.

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars) + 
  geom_point(aes(x=disp,y=mpg)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 16, color = "black"),
        axis.text.y = element_text(size = 16, color = "black"))

p2 <- ggplot(mtcars) + 
  geom_point(aes(x=hp,y=mpg)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 16, color = "black"),
        axis.text.y = element_text(size = 16, color = "black"))

ggarrange(p1,p2,nrow = 1)

The ideal output would look like this: 在此处输入图像描述

Just add axis.text.y = element_blank(), axis.title.y = element_blank()) to your code:

library(ggplot2)
library(ggpubr)

p1 <- ggplot(mtcars) + 
  geom_point(aes(x=disp,y=mpg)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 16, color = "black"),
        axis.text.y = element_text(size = 16, color = "black"))

p2 <- ggplot(mtcars) + 
  geom_point(aes(x=hp,y=mpg)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 16, color = "black"),
        axis.text.y = element_blank(),
        axis.title.y = element_blank())



ggarrange(p1,p2,nrow = 1)

在此处输入图像描述

You can pivot_longer your dataframes, and then use facet_wrap :

df = tidyr::pivot_longer(mtcars, cols=c("disp", "hp"))

ggplot(df) + 
  geom_point(aes(x=value,y=mpg)) +
  facet_wrap(vars(name)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 16, color = "black"),
        axis.text.y = element_text(size = 16, color = "black"))

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM