如何格式化我的y轴刻度值和我的geom_text以将逗号显示为千位分隔符?

时间:2017-07-13 06:47:19

标签: r ggplot2 formatting

我在R中运行以下代码:

options(scipen=99)

sp <- ggplot(mydata2, aes(x=FY, y=PkgRev, fill=FY, label=PkgRev)) + geom_bar(stat = "identity") +  
geom_text(aes(label=PkgRev),size=3,position=position_dodge(width=0.9),vjust=-0.50)

sp

sp + facet_grid(Market ~ PropertyCode) +
theme(axis.title.x=element_blank(),
    axis.text.x=element_blank(),
    axis.ticks.x=element_blank(),
    axis.title.y=element_blank()) +
theme(legend.position="bottom") + 
theme(legend.title=element_blank()) +
 ggtitle('xxxxxxxx') +
 scale_y_continuous(breaks = seq(0, 170100000, by=50000000), limits=c(0,170100000))

以上代码给出了以下输出(显示摘录):

image1

我希望用逗号分隔y轴刻度值,以便在显示条形顶部值的文本上表示数千个相同的原理。

我如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以使用scale包并添加&#34; labels = comma&#34;到你的scale_y_continuous() 请参阅此帖子了解轴 Thousand separator in label of x or y axis 这是针对geom_text的 including a comma separator for data labels in ggplot

所以:

sp <- ggplot(mydata2, aes(x=FY, y=PkgRev, fill=FY, label=PkgRev)) + 
    geom_bar(stat = "identity") + 
    geom_text(aes(label=comma(PkgRev)),size=3,
         position=position_dodge(width=0.9),vjust=-0.50)

sp + facet_grid(Market ~ PropertyCode) +
    theme(axis.title.x=element_blank(),
    axis.text.x=element_blank(),
        axis.ticks.x=element_blank(),
        axis.title.y=element_blank()) +
    theme(legend.position="bottom") + 
    theme(legend.title=element_blank()) +
     ggtitle('xxxxxxxx') +
     scale_y_continuous(breaks = seq(0, 170100000, by=50000000), 
     limits=c(0,170100000), labels = comma)

应该有效