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

如何在ggplot的geom_text标签中设置数值保留一位小数?

解决ggplot中geom_text标签小数位数过多的问题

问题描述

我在绘制ggplot图表时,实时计算geom_text的标签数值,结果返回的小数位数过多。请问如何将其设置为仅保留一位小数?以下是我的代码:

plot.title = paste0('Subjectivity by sentence cluster')
cb2<-ggplot(sent_txt, aes(x=as.factor(best_cl), fill=as.factor(subjectivity_bin3_labs)))+  
  geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) +  
  geom_text(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..], label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..]) ),            
            stat="count", position=position_dodge(0.9), vjust=-0.5)+  
  theme_minimal() +   
  scale_fill_viridis_d() +  
  labs(title=plot.title, subtitle = paste0('wordembedding: ', scope,', optimal method: ', best_method), fill="subjectivity class" ) +  
  xlab("cluster") +  
  ylab('subjectivity class, %') +  
  scale_y_continuous(labels = scales::percent) 
cb2
plot.nme = paste0(scope.prefix,'_',best_method_dr,'_',best_method_cl,'_sentence_subjectivity_distribution.png')
plot.store <-paste0(report.loc,plot.nme)
ggsave(plot.store, height = graph_height, width = graph_height * aspect_ratio, dpi=dpi)

解决方法

只需要在scales::percent()函数中添加accuracy = 0.1参数,就能让百分比标签只保留一位小数。accuracy参数用于控制百分比的精度:

  • accuracy = 0.1 → 保留一位小数
  • accuracy = 0.01 → 保留两位小数(默认值)

修改后的geom_text核心代码行如下:

geom_text(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..], label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..], accuracy = 0.1) ),            
          stat="count", position=position_dodge(0.9), vjust=-0.5)+  

完整修改后的代码

plot.title = paste0('Subjectivity by sentence cluster')
cb2<-ggplot(sent_txt, aes(x=as.factor(best_cl), fill=as.factor(subjectivity_bin3_labs)))+  
  geom_bar(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..]), position="dodge" ) +  
  geom_text(aes( y=..count../tapply(..count.., ..x.. ,sum)[..x..], label=scales::percent(..count../tapply(..count.., ..x.. ,sum)[..x..], accuracy = 0.1) ),            
            stat="count", position=position_dodge(0.9), vjust=-0.5)+  
  theme_minimal() +   
  scale_fill_viridis_d() +  
  labs(title=plot.title, subtitle = paste0('wordembedding: ', scope,', optimal method: ', best_method), fill="subjectivity class" ) +  
  xlab("cluster") +  
  ylab('subjectivity class, %') +  
  scale_y_continuous(labels = scales::percent) 
cb2
plot.nme = paste0(scope.prefix,'_',best_method_dr,'_',best_method_cl,'_sentence_subjectivity_distribution.png')
plot.store <-paste0(report.loc,plot.nme)
ggsave(plot.store, height = graph_height, width = graph_height * aspect_ratio, dpi=dpi)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 16:21:00