如何修复ggplot报错‘Error: Continuous value supplied to discrete scale’?
修复ggplot折线图报错:
Error: Continuous value supplied to discrete scale 问题根源
- 代码中引用的
v2x_regime字段不存在于你的数据集,实际应该用Index区分两组折线 - 即便存在
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
相关产品推荐
相关产品推荐

