简体   繁体   English

如何使 R 中 ggplot 图形的 y 轴标签重叠

[英]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.下面两个图的 y 轴是相同的(即mpg )并且具有相同的比例。 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.我希望左侧的图形与右侧图形的 y 轴重叠,这样您就只能看到右侧图形的 y 轴的刻度线。

The code below makes both figures and aligns them however you can still see the y-axis labels for the figure on the right.下面的代码生成两个图形并对齐它们,但是您仍然可以看到右侧图形的 y 轴标签。

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:理想的 output 如下所示: 在此处输入图像描述

Just add axis.text.y = element_blank(), axis.title.y = element_blank()) to your code:只需将axis.text.y = element_blank(), axis.title.y = element_blank())添加到您的代码中:

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 :您可以pivot_longer您的数据帧,然后使用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: Output:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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