在地标标签中添加千分之一的逗号

时间:2018-12-13 16:36:36

标签: r ggplot2 format

例如,我有以下数据:

eg_data_x <- data.frame(
period = c("1", "2", "1 + 2"),
grp = c("1", "2", "1 + 2"),
sum_period = c(20000, 30000, 50000))
eg_data_x$period <- factor(eg_data_x$period, levels = c("1", "2", "1 + 2"))
eg_data_x$grp <- factor(eg_data_x$grp, levels = c("1", "2", "1 + 2"))

我具有以下语法来创建条形图,该条形图按时段总计橡皮鸡。我将y轴标记为千分之几的逗号(1,000对1000)。

我需要以相同的方式向图形本身中的值添加一个逗号:20000、30000和50000需要变为20,000、30,000和50,000。我还没有找到ggplot2的文档,该文档解释了如何将其添加到图形值标签中。

如何将相同的逗号添加到图形本身的值中?

library(ggplo2)
total_chickens_by_period <-  (
(ggplot(data = eg_data_x, aes(x=period, y=sum_period, fill = grp)) +
 geom_bar(stat = "identity", color = "black")) +
scale_fill_manual(values = c("red", "green", "gold")) +
scale_y_continuous(labels = scales::comma) +
geom_text(aes(label = sum_period), position = position_stack(vjust = 0.9), fontface = "bold") +
ggtitle("Total Rubber Chickens by Period") + xlab("Period") + ylab("Chickens") +
theme(plot.title = element_text(color = "black", size = 14, face = "bold", hjust = 0.5),
      axis.title.x = element_text(color = "black", size = 12, face = "bold"), 
      axis.title.y = element_text(color = "black", size = 12, face = "bold")) +
labs(fill = "Period") )

total_chickens_by_period

1 个答案:

答案 0 :(得分:4)

您只需要使用formatbig.mark格式化数字(标签)(您可以将其直接传递给aes)。

library(ggplot2)
# Using OPs data
ggplot(eg_data_x, aes(period, sum_period, fill = grp)) +
    geom_bar(stat = "identity", color = "black") +
    scale_y_continuous(labels = scales::comma) +
    geom_text(aes(label = format(sum_period, big.mark = ",")), 
              position = position_stack(vjust = 0.9))

enter image description here