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

如何修复ggplot报错‘Error: Continuous value supplied to discrete scale’?

修复ggplot折线图报错:Error: Continuous value supplied to discrete scale

问题根源

  1. 代码中引用的v2x_regime字段不存在于你的数据集,实际应该用Index区分两组折线
  2. 即便存在v2x_regime,0/1的数值类型会被ggplot识别为连续变量,但你用了针对离散变量的scale_color_manual,导致类型不匹配报错

修复代码

library(ggplot2)
library(dplyr)

# 将Index转换为带自定义标签的因子(确保离散变量识别)
output1 <- output1 %>%
  mutate(Regime = factor(Index, levels = c(0, 1), labels = c("autocracy", "democracy")))

# 绘制分组折线图
ggplot(output1, aes(x = Year, y = SuPDem, color = Regime)) +
  geom_line(size = 0.6) +
  scale_color_manual(values = c("orange", "blue")) +
  theme_minimal(base_size = 5)

关键改动说明

  • 新增Regime列:把原Index的0/1转换为带明确业务标签的因子,让ggplot正确识别为离散分组变量
  • 简化绘图逻辑:无需多次调用geom_line,全局aes中指定color = Regime后,ggplot会自动按分组绘制对应折线
  • 完全匹配需求:0对应autocracy(橙色),1对应democracy(蓝色)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 13:25:15