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

R语言ggplot绘图Y轴未排序及连续刻度调用报错求助

问题成因
  • 构造初始数据时,所有变化率数值都用双引号包裹,且通过rbind()拼接为字符串矩阵,转换为数据框后sum1.visit_bush.、sum1.counts_bush.等列均为字符类型,而非数值类型
  • 数据融合后得到的df_month_cand_plot中y列继承了字符属性,你之前的代码调用scale_y_discrete()时,Y轴会按字符串的字典序排列,而非数值大小,所以显示混乱
  • 后续替换为scale_y_continuous()时,字符类型的y值无法匹配连续轴的数值输入要求,就会抛出Discrete value supplied to continuous scale报错
解决方法
  1. 首先修正数值列的类型,可二选一操作:
# 方法1:修改原始数据构造逻辑,去掉数值外的引号,改用c生成向量更合理
date1 <- c("February", "March",   "April",     "May",       "June",      "July",      "August",    "September", "October",   "November")
sum1.visit_bush. <- c(0, 0 ,1  , -0.75 ,2,0 ,0.333333333333333 , 1.25  , 0,  -1)
sum1.counts_bush. <- c(0 ,0.115290451813933, -0.557273997206146, 0.146270002253775 ,  0.100865119937082, 0.512412930880514,  0.435049598488427,   -0.0831961816984858, 0.824791311372408,  -0.156025577963601 )
sum1.hcounts_bush. <- c(0,  0.0387010676156584, -0.625695931477516, 0.47254004576659,  -0.233100233100233, 0.99290780141844 ,  -0.032536858159634 , 0.349973725696269 , 0.660957571039315,  -0.341223341926412)
evolution1 <- data.frame(date1, sum1.visit_bush., sum1.counts_bush., sum1.hcounts_bush.)

# 方法2:不想改动原始构造代码的话,直接批量转换数值列类型
evolution1[,2:4] <- lapply(evolution1[,2:4], function(x) as.numeric(as.character(x)))
  1. 修改绘图函数的Y轴配置:删除原来的scale_y_discrete(),替换为你需要的连续轴配置,可通过limits固定显示范围:
scale_y_continuous(breaks=seq(-1, 2, 0.25), limits = c(-1, 2))
  1. 可选优化:你示例代码中最开头的df_month_cand选列时写的列名是date,实际数据集的列名是date1,注意修正避免选列报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 00:45:07