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

ggplot2次坐标轴出现多条网格线:原因排查与解决方法

ggplot2 图表出现重复水平网格线问题解决

问题描述

使用以下代码绘图时,图表在0、20.31等位置出现多条重复的水平网格线:

library(ggplot2)
ggplot (structure(list(Group1 = c('A','B', 'B','A', 'B','B', 'A', 'B', 'B'), Val = c(40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59)), row.names = c(NA, -9L), class = "data.frame"), aes (x = Group1, y = Val)) +
geom_line () +
scale_y_continuous (breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54) ,
sec.axis = sec_axis(~.,
breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54)))

原因分析

重复网格线的根源是:你同时给主Y轴和次Y轴设置了完全一致的breaks参数。ggplot2会为每个轴独立生成对应刻度的网格线,当两个轴的刻度位置完全重合时,两条网格线叠在一起,视觉上就呈现出“重复”的效果。

解决方法

只需要在次轴的配置中关闭网格线的生成即可,通过guide = guide_axis(theme = theme(axis.grid = element_blank()))来隐藏次轴的网格线。

修改后的代码

library(ggplot2)
ggplot (structure(list(Group1 = c('A','B', 'B','A', 'B','B', 'A', 'B', 'B'), Val = c(40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59)), row.names = c(NA, -9L), class = "data.frame"), aes (x = Group1, y = Val)) +
geom_line () +
scale_y_continuous (
  breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54),
  sec.axis = sec_axis(
    ~.,
    breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54),
    guide = guide_axis(theme = theme(axis.grid = element_blank()))
  )
)

简化版代码(可选)

如果次轴的刻度和主轴完全一致,其实没必要重复设置breaks,可以简化成这样:

library(ggplot2)
ggplot (structure(list(Group1 = c('A','B', 'B','A', 'B','B', 'A', 'B', 'B'), Val = c(40.707, -22.513, -3.501, -12.884, -19.668,
-5.976, -16.721, -15.838, -5.59)), row.names = c(NA, -9L), class = "data.frame"), aes (x = Group1, y = Val)) +
geom_line () +
scale_y_continuous (
  breaks = c(0, -22.51, 20.31, 41.72, 63.13, 84.54),
  sec.axis = sec_axis(~., guide = guide_axis(theme = theme(axis.grid = element_blank())))
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 08:02:37