我正在尝试更改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)
这就是我得到的。使用逗号格式化将有助于提高可读性。
答案 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)
答案 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)
基于:Format number in R with both comma thousands separator and specified decimals