首页 > 解决方案 > 如何在 R 中的条形图标签上添加 $ 符号?[包括图像和代码]

问题描述

希望在我的 x 轴上的标签和条形图中的数字上添加美元符号。下面是我的代码和图表。

YTD_bar <- 
      ggplot(TYSales_LYSales, aes(x=as.character(FSCL_YR), y=SALES)) + geom_bar(stat="identity", fill="orange", color="grey40") + theme_bw() + coord_flip() + 
      geom_text(aes(x= as.character(FSCL_YR), y=0.01, label= SALES),
                hjust=-0.8, vjust=-1, size=3, 
                colour="black", fontface="bold",
                angle=360) + labs(title="D27 2020 YTD Sales v 2019 YTD Sales", x="Fiscal Year",y="Sales") + theme(plot.title=element_text(hjust=0.5))
    YTD_bar

在此处输入图像描述

在此处输入图像描述

标签: rggplot2

解决方案


scales 包(与 ggplot2 一起安装)具有将十进制值转换为货币的便捷功能dollarlabel_dollar()

请参阅帮助以了解可用于调整格式的可能选项。

library(ggplot2)
library(scales)

YTD_bar <- 
   ggplot(TYSales_LYSales, aes(x=as.character(FSCL_YR), y=SALES)) + 
   geom_bar(stat="identity", fill="orange", color="grey40") + 
   theme_bw() + coord_flip() + 
   geom_text(aes(x= as.character(FSCL_YR), y=0.01, label= dollar(SALES)),
             hjust=-0.8, vjust=-1, size=3, colour="black", fontface="bold", angle=360) + 
   labs(title="D27 2020 YTD Sales v 2019 YTD Sales", x="Fiscal Year",y="Sales") + 
   theme(plot.title=element_text(hjust=0.5)) +
   scale_y_continuous(labels = label_dollar())
YTD_bar

在此处输入图像描述


推荐阅读