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

ggplot图例显示小数,而数据列仅含17、18整数的问题求助

问题描述

数据列Number of years of data仅包含17和18两个整数值,但使用ggplot绘制散点图时,size属性对应的图例却显示小数数值。尝试用as.numeric()转换该列后问题仍存在,希望图例仅展示17和18两个值。

当前代码

plt <- ggplot(data=a,mapping=aes(x=distance, y=rate)) +
    geom_point(aes(size=as.numeric(`Number of years of data`),color=Trend))

当前图例效果

散点图图例显示小数刻度

解决方案

方法1:转为因子类型(推荐)

把目标列转为因子,让ggplot识别为离散变量,图例自动只显示存在的两个值:

plt <- ggplot(data=a,mapping=aes(x=distance, y=rate)) +
    geom_point(aes(size=factor(`Number of years of data`), color=Trend)) +
    scale_size_discrete(name = "Number of years of data")
  • 用factor()转换后,size映射会基于离散值,图例仅展示17和18
  • scale_size_discrete()用于保持图例名称和原列一致

方法2:手动指定连续刻度

如果需要保留数值型的size映射(比如让18对应的点更大),可以手动设置刻度:

plt <- ggplot(data=a,mapping=aes(x=distance, y=rate)) +
    geom_point(aes(size=as.numeric(`Number of years of data`), color=Trend)) +
    scale_size_continuous(breaks = c(17, 18), labels = c("17", "18"))
  • breaks参数指定要显示的刻度值,labels对应显示文本,强制图例只展示17和18

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:22:49