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

如何在ggplot饼图图例中显示整数而非浮点数?

解决ggplot饼图图例显示整数的方法

要让图例仅显示整数,可通过以下两种常用方式实现:

方法一:提前转换变量类型

在绘图前将FAIXA_DESENROLA转换为整数类型,图例自然会显示整数:

# 转换变量为整数
faixa_vol_op_contagem$FAIXA_DESENROLA <- as.integer(faixa_vol_op_contagem$FAIXA_DESENROLA)

# 绘制饼图
ggplot(faixa_vol_op_contagem, aes(x = "", y = num_vol_op, fill = FAIXA_DESENROLA)) +
  geom_bar(stat = "identity") +
  coord_polar("y", start = 0) +
  theme_void()

方法二:通过刻度函数自定义标签

若不想修改原始数据,可在绘图时用刻度函数将浮点数格式化为整数:

  • 若FAIXA_DESENROLA是离散型变量:
ggplot(faixa_vol_op_contagem, aes(x = "", y = num_vol_op, fill = FAIXA_DESENROLA)) +
  geom_bar(stat = "identity") +
  coord_polar("y", start = 0) +
  scale_fill_discrete(labels = function(x) as.integer(as.numeric(x))) +
  theme_void()
  • 若FAIXA_DESENROLA是连续型变量:
ggplot(faixa_vol_op_contagem, aes(x = "", y = num_vol_op, fill = FAIXA_DESENROLA)) +
  geom_bar(stat = "identity") +
  coord_polar("y", start = 0) +
  scale_fill_continuous(
    breaks = function(x) floor(x):ceiling(x),
    labels = function(x) as.integer(x)
  ) +
  theme_void()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 00:32:35