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

R ggplot2绘制双Y轴出现Discrete value报错问题求助

错误原因

你将month列转换为了字符型的月份缩写(如Sep/Oct),属于离散分类变量,但代码中调用的scale_x_continuous()仅支持连续数值型的X轴变量,变量类型不匹配直接触发了该报错。
此外还有两个隐藏问题需要同步修复:

  • 字符型月份默认按字母顺序排序,会出现Jan/Feb排在Sep前面的顺序错乱问题
  • 离散X轴上绘制折线时需要指定group=1,否则ggplot会认为每个月份是独立分组无法生成连续折线

修复后完整代码

library(tidyverse)
monthly_trend <- read_csv("monthly_trend.csv")
monthly_trend$month <- month.abb[monthly_trend$month]
# 将月份转为有序因子,按实际时间顺序设置层级
monthly_trend$month <- factor(monthly_trend$month, 
                              levels = c("Sep", "Oct", "Nov", "Dec", "Jan", "Feb"), 
                              ordered = TRUE)

ggplot(data = monthly_trend) + 
  geom_col(mapping = aes(x = month, y = tot_num_of_rides)) +
  # 增加group=1保证折线正常绘制
  geom_line(mapping = aes(x = month, y = avg_temp*32000, group = 1)) + 
  # 改用离散X轴的scale配置
  scale_x_discrete(name = "month") +
  scale_y_continuous(name = "num_of_rides", sec.axis = sec_axis(~./32000, name = "avg_temp"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 00:39:00