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

修改ggplot2地图图例外观:解决连续值适配离散刻度报错

问题解决:将渐变图例改为独立色块图例

报错原因

Continuous value supplied to discrete scale错误的核心原因是:你的prop是连续数值型变量,而scale_fill_manual是专门为离散分类变量设置颜色的刻度函数,两者类型不匹配导致报错。

解决方法

需要先把连续的prop变量按指定断点分成离散类别,再配合scale_fill_manual实现独立色块效果:

  1. 先对数据进行分箱处理,生成离散分类变量:
# 对prop进行分箱,生成对应类别的离散变量
gazole_map$prop_cat <- cut(
  gazole_map$prop,
  breaks = c(my_breaks, Inf),  # 用Inf覆盖"15以上"的区间
  labels = my_labels,
  include.lowest = TRUE  # 确保最小值0被包含在第一个区间内
)
  1. 修改ggplot代码,将填充映射改为分箱后的离散变量,并替换刻度函数:
my_plot <- ggplot() +
  geom_sf(data = gazole_map, aes(fill = prop_cat, geometry = geometry)) +  # 替换为分箱后的变量
  theme_void() +
  scale_fill_manual(values = my_palette, labels = my_labels) +  # 使用scale_fill_manual
  
  # 保留原有标题、主题等设置
  ggtitle("Stations en rupture de gazole en métropole") +
  labs(subtitle = paste0(Sys.Date() - 1)) +
  theme(
    plot.margin = unit(c(1, 1, 1, 1), "lines"),
    legend.position = "right",
    legend.box = "vertical",
    legend.key.width = unit(0.3, "cm"),
    legend.key.height = unit(1, "cm"),
    legend.title = element_blank(),
    legend.title.align = 1,
    legend.text.align = 0.5,
    plot.caption = element_text(hjust = 0, size = 8, margin = margin(t = 10))
  ) +
  labs(caption = "Source : Ministère de l'Economie")

关键说明

  • breaks = c(my_breaks, Inf)是为了覆盖"15%"以上的所有数值,匹配你设置的最后一个标签"Plus de 15%"
  • include.lowest = TRUE确保0这个最小值被划分到第一个区间"Moins de 2%"中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:53:25