R geom_col 和 geom_text 标签使用美元符号和逗号

R geom_col and geom_text label using dollar signs and commas

我正在使用以下 table:

structure(list(Entity = structure(c(2L, 2L, 2L, 2L, 2L, 2L), .Label = c(" ", 
"FL", "MA", "WV"), class = "factor"), Area = c("Broward", "Broward", 
"Broward", "Broward", "Broward", "Broward"), `Store #` = c(1143, 
1023, 1067, 1030, 1091, 1019), Store = c("Boca Raton", "Deerfield Beach", 
"Delray Beach", "Fort Lauderdale", "Tamarac", "Boynton Beach"
), `Order Count` = c(18, 25, 26, 60, 34, 29), `Net Sales` = c(2420, 
3073, 3157, 6571, 3078, 2537), `Discount %` = c(0.202, 0.257, 
0.304, 0.242, 0.216, 0.22), AOT = c(134, 123, 121, 110, 91, 87
), ` ...9` = c(" ", " ", " ", " ", " ", " "), ` ...10` = c(" ", 
" ", " ", " ", " ", " ")), row.names = c(NA, -6L), class = c("tbl_df", 
"tbl", "data.frame"))

我创建了以下可视化效果:

example_table %>%
  group_by(Entity) %>%
  summarize(Avg_AOT = mean(AOT)) %>%
  ggplot(aes(x = Entity, y = Avg_AOT, fill = Entity)) +
  geom_col() +
  labs(title = "Title", subtitle = "Subtitle") +
  theme(plot.title = element_text(face = "bold")) +
  scale_fill_manual(values=met.brewer("Hiroshige", 6)) +
  geom_text(aes(label = round(Avg_AOT, 1)), position = position_dodge(0.6), vjust = -0.3) +
  scale_y_continuous(labels = label_dollar())
  

我已经使用 scale_y_continuous(labels = label_dollar())

成功制作了带有美元符号的 y 轴标签

但我怎样才能使条形图上方的标签也使用美元符号和逗号? (逗号不适用于这种情况,但它必须适用于其他情况,所以我也在寻找一个灵活的解决方案。)

只需将标签美学包裹在scales::dollar

example_table %>%
  group_by(Entity) %>%
  summarize(Avg_AOT = mean(AOT)) %>%
  ggplot(aes(x = Entity, y = Avg_AOT, fill = Entity)) +
  geom_col() +
  labs(title = "Title", subtitle = "Subtitle") +
  theme(plot.title = element_text(face = "bold")) +
  scale_fill_manual(values=MetBrewer::met.brewer("Hiroshige", 6)) +
  geom_text(aes(label = scales::dollar(round(Avg_AOT, 1))), 
            position = position_dodge(0.6), vjust = -0.3, size = 8) +
  scale_y_continuous(labels = scales::dollar_format())

另一种选择是在 geom_text()

中使用 paste0
library(MetBrewer)
library(tidyverse)

example_table %>%
  group_by(Entity) %>%
  summarize(Avg_AOT = mean(AOT)) %>%
  ggplot(aes(x = Entity, y = Avg_AOT, fill = Entity)) +
  geom_col() +
  labs(title = "Title", subtitle = "Subtitle") +
  theme(plot.title = element_text(face = "bold")) +
  scale_fill_manual(values=met.brewer("Hiroshige", 6)) +
  geom_text(aes(label = paste0(round(Avg_AOT, 1), "$")), position = position_dodge(0.6), vjust = -0.3) +
  scale_y_continuous(labels = label_dollar())