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

如何在堆叠柱状图添加数据点?geom_point报错问题求助

解决堆叠柱状图添加geom_point时的离散/连续刻度错误问题

我帮你分析下这个报错的核心原因,然后一步步解决它~

你遇到的"Discrete value supplied to continuous scale"错误,本质是变量类型不匹配:你的nb_species是字符型(存的是"NA"、"3"这类字符串),但绘图的y轴是连续数值型(pre_value、tem_value都是数字),把字符型数据放到连续刻度的轴上,ggplot自然会报错。另外,数据里的"NA"是字符串,不是R认可的缺失值,也会干扰绘图逻辑。


第一步:预处理数据,修正变量类型

先把nb_species转换成数值型,同时把字符串"NA"替换成R的真实缺失值:

library(dplyr)
complet_b <- complet_b %>%
  mutate(nb_species = as.numeric(nb_species))

处理后,nb_species会变成数值型,无效的"NA"字符串会自动转为R的NA,ggplot能正确识别这些缺失值。


第二步:调整ggplot代码,添加geom_point

同时修正你原代码里重复设置标签、标题的问题,给点设置合适的位置:

library(ggplot2)

# 绘图
ggplot(data = complet_b, aes(x = x)) +
  # 绘制降水堆叠柱状图
  geom_bar(aes(y = pre_value, fill = pre_type), 
           stat = "identity", width = 0.3) +
  # 绘制温度堆叠柱状图
  geom_bar(aes(x = x + 0.4, y = tem_value, fill = tem_type), 
           stat = "identity", width = 0.3) +
  # 添加nb_species数据点,放在两组柱状的中间位置
  geom_point(aes(x = x + 0.2, y = nb_species), 
             color = "darkred", size = 3, na.rm = TRUE) +
  # 设置x轴刻度
  scale_x_continuous(breaks = 1:3, 
                     labels = unique(complet_b$year_month)) +
  # 统一设置所有标签与标题
  labs(x = "Date", 
       y = "Number of Days", 
       title = "Precipitation & Temperature per Month",
       fill = "Frequency")

关键调整说明

  • x = x + 0.2:让点刚好落在降水柱(x位置)和温度柱(x+0.4位置)的中间,视觉更协调
  • na.rm = TRUE:忽略缺失值,避免ggplot尝试绘制无效的NA点
  • 用labs()统一设置标签,避免原代码中重复设置导致的覆盖问题

这样修改后,就能成功在堆叠柱状图上添加nb_species的数据点,不会再出现刻度类型不匹配的报错啦~

内容的提问来源于stack exchange,提问作者Elodie P.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 07:27:39