向每月总计的条形图添加标签

问题描述 投票:0回答:2

我在 R 中构建了一个条形图,其中每个条形代表一年中给定月份的累积降雨量。然而,酒吧本身没有标签,而我的老板确实强调他们应该有标签。当我尝试添加标签时,它总是添加比我需要的更多的东西。有什么建议吗?

这是我现在使用的代码:

code and image of plot

r ggplot2 label bar-chart summary
2个回答
0
投票

看起来您可能需要首先汇总数据,您的绘图结合了该月的所有值,因此当您对其进行标记时,它会标记每个 terra::plot(rnaturalearth::ne_countries(returnclass = "sf")["几何”])ortino 酒吧。如果您使用 prism2018 <-prism2018 %>$ group_by(Month)%>%summarise(ppt=sum(ppt)) 那么您应该每月获得一个值来标记。


0
投票

问题是您没有像对条形图那样按月在

geom_text
中汇总数据,即您必须使用
stat_summary
geom="text"
作为标签。否则你每个月都会有多个标签。

但是,恕我直言,一种更简单的方法是将数据框聚合到

ggplot()
之外。

使用一些虚假的随机示例数据:

library(ggplot2)
library(dplyr, warn=FALSE)

set.seed(123)

prism2018 <- data.frame(
  Month = rep(
    seq.Date(as.Date("2018-01-01"), as.Date("2018-12-01"), by = "month"),
    10
  ),
  `ppt (inches)` = runif(120),
  check.names = FALSE
)

prism2018 |>
  group_by(Month) |>
  summarise(`ppt (inches)` = sum(`ppt (inches)`, na.rm = TRUE)) |>
  ggplot(aes(Month, `ppt (inches)`)) +
  geom_col() +
  geom_text(
    aes(label = prettyNum(`ppt (inches)`, digits = 3)),
    vjust = 0, position = position_nudge(y = .05)
  )

© www.soinside.com 2019 - 2024. All rights reserved.