You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

ggplot2中调整facet_wrap面板标题及坐标轴位置(含轴翻转与反转)

调整ggplot2 facet_wrap面板的标题与坐标轴位置

我来帮你搞定这个面板图的调整需求!先从你的示例数据出发,一步步拆解操作:


第一步:先整理示例数据集

首先把你给出的数据转换成可直接复用的格式:

library(ggplot2)

# 构建示例数据集
df <- data.frame(
  Position = c(rep("S07", 11), rep("S08", 4)),
  Depth = c(1000, 1000, 1000, 120, 400, 400, 120, 25, 120, 25, 400, 200, 200, 400, 25),
  Var = c("SFA", "MFA", "DFA", "SFA", "MFA", "DFA", "SFA", "SFA", "DFA", "SFA", "DFA", "SFA", "SFA", "MFA", "SFA"),
  Value = c(0.5885938, 0.6228922, 0.6276554, 0.7342712, 0.379946, 0.6565114, 0.7330876, 0.7505527, 0.461091, 0.6202075, 0.427386, 0.6237663, 0.6275681, 0.4675334, 0.6647344)
)

第二步:还原你已完成的基础绘图

先写出包含坐标轴翻转x轴反转的基础代码:

# 基础绘图:已完成翻转+反转操作
base_plot <- ggplot(df, aes(x = Depth, y = Value, color = Var)) +
  geom_point(size = 2) +
  facet_wrap(~Position) +
  coord_flip() +  # 翻转x/y轴
  scale_x_reverse()  # 反转x轴(注意:coord_flip后Depth对应新的x轴)

base_plot

第三步:调整面板标题(Facet Strip)

1. 快速改变标题位置

facet_wrapstrip.position参数可以直接把标题放到四个方向:

  • 默认是"top",可选值还有"bottom""left""right"
    比如配合coord_flip,把标题放到右侧会更协调:
base_plot + facet_wrap(~Position, strip.position = "right")

2. 精细调整标题样式

如果要修改字体、对齐方式、背景,用theme()里的参数:

base_plot + 
  facet_wrap(~Position, strip.position = "right") +
  theme(
    strip.text = element_text(size = 12, face = "bold", hjust = 0),  # 标题字体加粗、左对齐
    strip.background = element_rect(fill = "#f5f5f5", color = "gray"),  # 标题背景浅灰+灰色边框
    strip.placement = "outside"  # 标题放在面板边框外(默认是inside)
  )

第四步:调整坐标轴位置与样式

1. 调整坐标轴标签位置

修改x/y轴标签的对齐方式、间距:

base_plot +
  theme(
    axis.title.x = element_text(hjust = 1, margin = margin(t = 10)),  # x轴标签右对齐,与轴间距10pt
    axis.title.y = element_text(hjust = 0, margin = margin(r = 10))   # y轴标签左对齐,与轴间距10pt
  )

2. 移动坐标轴本身

比如把y轴(翻转后对应Value的轴)移到右侧:

base_plot + scale_y_continuous(position = "right")

3. 调整坐标轴刻度样式

修改刻度的旋转角度、对齐方式:

base_plot +
  theme(
    axis.text.x = element_text(angle = 0, vjust = 0.5),  # x轴刻度水平居中
    axis.text.y = element_text(hjust = 1)  # y轴刻度右对齐
  )

最终组合示例

把以上调整整合起来,得到一个样式规整的面板图:

ggplot(df, aes(x = Depth, y = Value, color = Var)) +
  geom_point(size = 2) +
  facet_wrap(~Position, strip.position = "right") +
  coord_flip() +
  scale_x_reverse() +
  labs(x = "Depth", y = "Value", color = "Variable") +
  theme(
    strip.text = element_text(size = 12, face = "bold", hjust = 0),
    strip.background = element_rect(fill = "#f5f5f5", color = "gray"),
    axis.title.x = element_text(hjust = 1, margin = margin(t = 10)),
    axis.title.y = element_text(hjust = 0, margin = margin(r = 10)),
    axis.text.x = element_text(vjust = 0.5),
    panel.background = element_rect(fill = "white", color = "gray")
  )

内容的提问来源于stack exchange,提问作者Jellz

火山引擎 最新活动