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

如何将ggpubr包中ggbarplot的数据标签改为百分比格式?

问题:ggpubr条形图数据标签如何设置为百分比格式

我是R语言新手,使用ggpubr包绘制ggbarplot条形图时,已经把y轴刻度设置为百分比格式(比如显示80%而非0.8),但没法把数据标签也改成百分比格式。

我的代码如下:

ggbarplot(x = "Trophic level",
            y = "percent.present",
            fill = "Structure type",
            color = "Structure type",
            position = position_dodge(), 
            ylab = "% of species that used underpasses",
            ggtheme = theme_bw(), 
            title = "Proportion of species in area that used underpasses",
            palette = "Set2",
            label = TRUE, lab.nb.digits = 2) %>%
  ggpar(legend = "bottom") +
  yscale("percent", .format = TRUE)

生成的图表里数据标签显示为0.8而非80%,我的数据如下:

structure(list(`Trophic level` = c("Apex predator", "Apex predator", 
"Megaherbivore", "Megaherbivore"), `Structure type` = c("All underpasses", 
"Non-viaduct culverts", "All underpasses", "Non-viaduct culverts"
), percent.present = c(1, 1, 0.8, 0.2)), row.names = c(NA, -4L
), class = c("tbl_df", "tbl", "data.frame"))

请问怎么修改代码,让数据标签也显示为百分比格式?


解决方案

要让数据标签显示为百分比格式,你可以放弃label = TRUE的默认设置,手动用scales::percent()函数将数值转换为百分比格式,具体修改步骤如下:

  1. 移除原代码中的label = TRUE和lab.nb.digits = 2参数
  2. 添加label = scales::percent(percent.present)来生成百分比格式的标签
  3. 可选:通过lab.pos设置标签位置("in"为条形内部,"out"为外部),lab.vjust微调垂直位置

修改后的完整代码:

library(ggpubr)
library(scales)

ggbarplot(x = "Trophic level",
          y = "percent.present",
          fill = "Structure type",
          color = "Structure type",
          position = position_dodge(), 
          ylab = "% of species that used underpasses",
          ggtheme = theme_bw(), 
          title = "Proportion of species in area that used underpasses",
          palette = "Set2",
          label = scales::percent(percent.present), # 手动指定百分比标签
          lab.pos = "in", # 可选:设置标签在条形内部
          lab.vjust = 1.5) %>% # 可选:微调标签垂直位置
  ggpar(legend = "bottom") +
  yscale("percent", .format = TRUE)

修改后的数据标签会显示为100%、80%、20%这类格式,和y轴刻度保持一致。如果需要控制百分比的小数位数,可给scales::percent()添加accuracy参数,比如scales::percent(percent.present, accuracy = 1)显示整数百分比,accuracy = 0.1则显示一位小数。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 06:35:46