如何使用ggplot更改数据标签上的格式

时间:2018-01-02 21:18:54

标签: r ggplot2

我正在尝试更改ggplot上数据标签(到逗号)中数字的格式,但无法找到答案。你可以帮忙:))

以下是示例:

library("scales")
library("tidyverse")
df = tibble(year = as.factor(c(2016,2016,2017,2017)),
        kpi = c("value", "volume","value", "volume"),
        values = c(99999,8888,111111,11000)) 
df %>%
ggplot()+
aes(year,values, fill = kpi) +
geom_col() +
scale_y_continuous(labels = comma) +
stat_summary(fun.y = sum,
           aes(label = ..y..,
               group = year),
           geom = "text",
           vjust = 1,
           size =3) +
labs(title = "KPI By Year",
     fill = "KPIs",
     y = NULL,x = "Year")+
theme(legend.position="bottom")+
facet_wrap(~kpi, scales = "free_y", ncol = 1)

这就是我得到的。使用逗号格式化将有助于提高可读性。

enter image description here

2 个答案:

答案 0 :(得分:3)

一种方法是在label语句中使用format函数,参数为' big.mark =",":

df %>%
  ggplot()+
  aes(year,values, fill = kpi) +
  geom_col() +
  scale_y_continuous(labels = comma) +
  stat_summary(fun.y = sum,
               aes(label = format(..y.., big.mark = ","),
                   group = year),
               geom = "text",
               vjust = 1,
               size =3) +
  labs(title = "KPI By Year",
       fill = "KPIs",
       y = NULL,x = "Year")+
  theme(legend.position="bottom")+
  facet_wrap(~kpi, scales = "free_y", ncol = 1)

enter image description here

答案 1 :(得分:2)

只需将label = ..y..更改为label = format(as.numeric(..y..), nsmall=0, big.mark=",")

即可
library("scales")
library("tidyverse")
df = tibble(year = as.factor(c(2016,2016,2017,2017)),
            kpi = c("value", "volume","value", "volume"),
            values = c(99999,8888,111111,11000)) 
df %>%
  ggplot()+
  aes(year,values, fill = kpi) +
  geom_col() +
  scale_y_continuous(labels = comma) +

  stat_summary(fun.y = sum,
               aes(label = format(as.numeric(..y..), nsmall=0, big.mark=","),
                   group = year),
               geom = "text",
               vjust = 1,
               size =3) +


  labs(title = "KPI By Year",
       fill = "KPIs",
       y = NULL,x = "Year")+
  theme(legend.position="bottom")+
  facet_wrap(~kpi, scales = "free_y", ncol = 1)

enter image description here

基于:Format number in R with both comma thousands separator and specified decimals