在 ggplot 中的多面板图上聚集 x 轴刻度

Bunched up x axis ticks on multi panelled plot in ggplot

我正在尝试从三个单独的绘图中制作一个多面板绘图(参见图像)。但是,当绘图采用多面板格式时,我无法纠正成束的 x 轴刻度标签。以下是单个图和多面板的脚本:

个人剧情:

NewDat [[60]]
EstRes <- NewDat [[60]]

EstResPlt = ggplot(EstRes,aes(Distance3, `newBa`))+geom_line() + scale_x_continuous(n.breaks = 10, limits = c(0, 3500))+ scale_y_continuous(n.breaks = 10, limits = c(0,25))+ xlab("Distance from Core (μm)") + ylab("Ba:Ca concentration(μmol:mol)") + geom_hline(yintercept=2.25, linetype="dashed", color = "red")+ geom_vline(xintercept = 1193.9, linetype="dashed", color = "grey")+ geom_vline(xintercept = 1965.5, linetype="dashed", color = "grey") + geom_vline(xintercept = 2616.9, linetype="dashed", color = "grey") + geom_vline(xintercept = 3202.8, linetype="dashed", color = "grey")+ geom_vline(xintercept = 3698.9, linetype="dashed", color = "grey") 
 
EstResPlt 

多面板图:

MultiP <- grid.arrange(MigrPlt,OcResPlt,EstResPlt, nrow =1)

我试图包括:

MultiP <- grid.arrange(MigrPlt,OcResPlt,EstResPlt, nrow =1)+ 
  theme(axis.text.x = element_text (angle = 45)) )
MultiP

但只收到错误。不必包含所有刻度线。初始值、中间值和最终值就足够了,因此不需要将它们全部包括在内或倾斜。我只是不确定该怎么做。将不胜感激。

我认为用一个例子来展示会更好。

我的意思是,你用 MigrPltOcResPltEstResPlt 分别制作了 ggplot() +.....。对于要旋转 x 轴的图,添加 + theme(axis.text.x = element_text (angle = 45)).

例如,在iris数据中,只旋转x轴文本a like

a <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) +
  geom_point() + 
  theme(axis.text.x = element_text (angle = 45))
b <- ggplot(iris, aes(Petal.Width, Petal.Length)) +
  geom_point() 

gridExtra::grid.arrange(a,b, nrow = 1)

有几个选项可以解决拥挤的轴。让我们考虑以下与您的情况相似的示例。默认的标签策略不会使 x 轴过度拥挤。

library(ggplot2)
library(patchwork)
library(scales)

df <- data.frame(
  x = seq(0, 3200, by = 20),
  y = cumsum(rnorm(161))
)

p <- ggplot(df, aes(x, y)) +
  geom_line()

(p + p + p) / p &
  scale_x_continuous(
    name = "Distance (um)"
  )

但是,由于您已将 n.breaks = 10 设置为体重秤,它变得很拥挤。所以一个简单的解决方案就是删除它。

(p + p + p) / p &
  scale_x_continuous(
    n.breaks = 10, 
    name = "Distance (um)"
  )

或者,您可以将微米转换为毫米,这样可以减少标签的宽度。

(p + p + p) / p &
  scale_x_continuous(
    n.breaks = 10,
    labels = label_number(scale = 1e-3, accuracy = 0.1),
    name = "Distance (mm)"
  )

另一种选择是每隔 n 个单位放置一个中断,在下面的例子中,一个 1000。这恰好与偶然省略 n.breaks = 10 相吻合。

(p + p + p) / p &
  scale_x_continuous(
    breaks = breaks_width(1000), 
    name = "Distance (um)"
  )

reprex package (v2.0.1)

于 2021-11-02 创建