【问题标题】:How to change the format on data labels with ggplot [closed]如何使用 ggplot 更改数据标签的格式 [关闭]
【发布时间】:2018-01-02 21:18:53
【问题描述】:

我正在尝试更改 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)

这就是我得到的。用逗号格式化对可读性有很大帮助。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

一种方法是在标签语句中使用带有参数 '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)

【讨论】:

    【解决方案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

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 1970-01-01
      相关资源
      最近更新 更多