R使用ggplot绘图报错Discrete value supplied to continuous scale如何解决
报错原因
你遇到的报错核心是x轴数据类型与坐标轴设置不匹配:
你在aes中使用format(Date,"%d")提取日期中的日信息,该函数返回的是字符类型(属于离散值),但后续你调用了scale_x_continuous()为x轴配置连续型刻度,离散值无法适配连续坐标轴的要求,因此触发该报错。
另外代码还存在一个语法瑕疵:你用%>%管道符将weather2数据集传入ggplot后,不需要再在ggplot()参数中重复传入weather2,重复传参会增加映射逻辑冲突的概率。
修复后完整代码
Asnow <- weather2 %>% ggplot(mapping = aes(as.numeric(format(Date,"%d")), (MinTemp+MaxTemp)/2)) + geom_point(aes(group = as.numeric(format(Date,"%m")), color = as.numeric(format(Date,"%m"))), size = 1) + xlab("Days per Month") + ylab("Temperature in US during the year") + scale_x_continuous(breaks = seq(0, 32, 4)) + scale_y_continuous(breaks = seq(0, 100, 20)) + facet_wrap(~as.numeric(format(Date,"%m"))) + annotate("rect", xmin = 0, xmax = 32, ymin = 0, ymax = 32, alpha = .2) + labs(title = "Probability of snowing") Asnow
改动说明
- 给
format(Date,"%d")套上as.numeric(),将x轴映射值转为数值型,匹配连续x轴的设置要求 - 删除ggplot()中重复传入的weather2数据集,符合管道符传参的语法规则
- 将所有
format(Date,"%m")也转为数值型,避免月份排序异常、颜色映射不符合预期的问题
内容的提问来源于stack exchange,提问作者pls help
相关产品推荐
相关产品推荐

