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

如何使用R ggplot2绘制带百分比标签的堆叠条形图并调整数值格式

堆叠百分比条形图调整方案

依赖包准备

首先需要提前加载scales包用于百分比格式化,未安装的可以先执行install.packages("scales")。

核心修改点

  • 数值标签格式化:将geom_text的label参数传入scales::percent(THW, accuracy = 1),即可直接把小数转换为整数百分比格式,比如-0.02自动转为-2%。
  • x轴百分比适配:增加scale_x_continuous(labels = scales::percent_format(accuracy = 1))配置x轴刻度为百分比格式,同时删除原代码中theme(axis.text.x=element_blank())语句以显示x轴刻度,另外补全原代码中缺失的x轴文本角度参数(示例补为0,可根据需求调整)。
# 加载依赖包
library(ggplot2)
library(scales)

# 原数据预处理代码保持不变
df$Country<- factor(df$Country,levels = c( "Australia","Austria", "Belgium","Canada","Denmark","Finland",
                                           "France","Germany","Greece","Iceland","Ireland","Italy",
                                           "Japan", "Luxembourg", "Netherlands","New Zealand","Norway","Portugal", 
                                           "Spain" ,"Sweden","Switzerland","Turkey", "United Kingdom", "United States" ))

df$Data<- factor(df$Data,levels = c("TED 2003 (adjusted)", "OECD 2003 (adjusted)"))

# 调整后的绘图代码
plot <- ggplot(df, aes(x=THW, y=Country, fill=Data, label = scales::percent(THW, accuracy = 1))) +  
  geom_bar(stat = "identity") + 
  geom_text(size = 4, position = position_stack(vjust = 0.5), color="black", fontface="bold") +
  labs(x="调整后百分比值", y="", title="", fill="数据来源:") +
  theme_bw() +
  # 补全缺失的angle参数,此处设为0可按需修改
  theme(axis.text.x = element_text(angle = 0, hjust = 1, family="Times", face="bold", size=12, color="black"), 
        axis.title.x = element_text(family="Times", face="bold", size=16, color="black"),
        axis.text.y = element_text(family="Times", face="bold", size=12, color="black"),
        axis.title.y = element_text(family="Times", face="bold", size=16, color="black"),
        strip.text = element_text(size=15, face="bold"),
        plot.title = element_text(size=20, face="bold")) +
  theme(legend.title = element_text(family="Times", face="bold", size=16, color="black"),
        legend.text = element_text(family="Times", color = "black", size = 16,face="bold"),
        legend.position="right",
        legend.box = "vertical",
        plot.title = element_text(hjust = 0.5)) +
  scale_y_discrete() +
  # 新增x轴百分比格式配置
  scale_x_continuous(labels = percent_format(accuracy = 1))

如果需要保留小数位的百分比,只需要修改accuracy参数即可,比如accuracy = 0.1就会显示为-2.0%的格式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 17:36:02