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

ggplot2中scale_y_continuous添加次坐标轴报错及绘图问题求助

问题解决:ggplot折线图无显示及次坐标轴报错

1. geom_line无显示问题

原因

x轴使用的是factor类型的月份,ggplot默认按x的每个类别分组,每个月份对应一个独立组,每组仅1个观测值,无法形成连续折线,因此触发提示Each group consists of only one observation。

解决方法

在aes中添加group=1,强制将所有数据归为同一组,让ggplot识别需要连接所有点。

修正代码

df |> ggplot(aes(x=Month))+
  geom_line(aes(y=AR2019, group=1))

2. scale_y_continuous报错问题

原因

geom_segment的xend参数传入了离散的Month因子,而连续型y轴要求坐标参数为数值类型,类型不匹配导致报错Discrete value supplied to continuous scale。

解决方法

将Month因子转换为整数(利用因子的有序性,as.integer(Month)会返回1-12的连续数值),同时调整xend和yend的对应逻辑,确保所有坐标参数为数值类型,最后将x轴刻度标签还原为月份缩写。

修正代码

df |> 
  mutate(Month_num = as.integer(Month)) |> 
  ggplot(aes(x=Month_num)) +
  geom_segment(aes(
    y=AR2019/3, 
    xend=c(tail(Month_num, n=-1), NA), 
    yend=c(tail(AR2019/3, n=-1), NA))
  ) +
  geom_segment(aes(
    y=AMXT2019, 
    xend=c(tail(Month_num, n=-1), NA), 
    yend=c(tail(AMXT2019, n=-1), NA))
  ) +
  scale_x_continuous(
    breaks = 1:12,
    labels = month.abb
  ) +
  scale_y_continuous(
    name = 'Average Annual Rainfall',
    sec.axis = sec_axis(~. *3, name = 'Monthly Temperature (°C)')
  )

更简洁的替代方案

直接用geom_line实现双折线+次坐标轴,无需使用geom_segment:

df |> ggplot(aes(x=Month)) +
  geom_line(aes(y=AR2019/3, group=1), color="#2E86AB") +
  geom_line(aes(y=AMXT2019, group=1), color="#F24C4C") +
  scale_y_continuous(
    name = 'Average Annual Rainfall',
    sec.axis = sec_axis(~. *3, name = 'Monthly Temperature (°C)')
  )

内容的提问来源于stack exchange,提问作者George K-Agyen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 03:53:21