You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot图表中心创建新轴并添加类默认的X/Y轴标签?

在ggplot中添加自定义轴及匹配样式的标签

如果要给已有ggplot图添加额外的轴,并让标签样式和默认轴一致,可根据需求选择两种方案:

方法1:完全独立的自定义轴(无数值转换关系)

用geom_line绘制轴的线条,配合annotate添加标签,通过参数调整让样式匹配默认轴:

library(ggplot2)

# 示例数据
df <- data.frame(
  x = 1:10,
  y_main = runif(10, 0, 10),
  y_extra = runif(10, 0, 100)
)

# 基础绘图
base_plot <- ggplot(df, aes(x, y_main)) +
  geom_line(color = "#2196F3") +
  labs(x = "原始X轴", y = "原始Y轴") +
  theme_minimal(base_size = 12)

# 添加右侧自定义Y轴
base_plot <- base_plot +
  # 绘制轴的竖线
  geom_line(aes(x = max(x) + 0.5, y = y_extra/10), color = "#F44336", linetype = "solid") +
  # 添加轴标签(角度、位置、大小匹配默认轴)
  annotate("text", x = max(x) + 1, y = mean(y_extra)/10, 
           label = "新Y轴", angle = 90, size = 4.5, color = "black") +
  # 可选:添加刻度标签
  annotate("text", x = max(x) + 0.7, y = seq(0, 10, 2), 
           label = seq(0, 100, 20), size = 3.5, color = "black")

# 添加顶部自定义X轴
base_plot <- base_plot +
  # 绘制轴的横线
  geom_line(aes(x = x, y = max(y_main) + 0.5), color = "#4CAF50", linetype = "solid") +
  # 添加轴标签
  annotate("text", x = mean(x), y = max(y_main) + 1.2, 
           label = "新X轴", size = 4.5, color = "black") +
  # 可选:添加刻度标签
  annotate("text", x = seq(2, 10, 2), y = max(y_main) + 0.7, 
           label = seq(40, 120, 20), size = 3.5, color = "black")

# 调整边距给新轴留空间
base_plot + theme(plot.margin = margin(60, 60, 20, 20))

方法2:官方支持的副轴(有数值转换关系)

如果新轴和原轴存在固定数值转换关系,推荐用sec_axis,样式会自动匹配默认轴:

ggplot(df, aes(x, y_main)) +
  geom_line(color = "#2196F3") +
  # 绘制对应新轴的线条
  geom_line(aes(y = y_extra/10), color = "#F44336") +
  # 设置Y轴副轴
  scale_y_continuous(
    name = "原始Y轴",
    sec.axis = sec_axis(~ . * 10, name = "新Y轴")  # 转换规则:新轴值 = 原轴值 × 10
  ) +
  # 设置X轴副轴(示例转换规则)
  scale_x_continuous(
    name = "原始X轴",
    sec.axis = sec_axis(~ . * 12, name = "新X轴")
  ) +
  theme_minimal(base_size = 12)

两种方案中,sec_axis是ggplot官方原生方案,样式完全对齐默认轴;如果需要完全独立的无转换轴,就用geom_line+annotate的组合,通过调整size、angle、位置参数匹配默认样式。

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 17:07:38