沿着每个面的密度图的中心平均值画一条线

Drawing a line down the centre mean of the density plots for EACH facet

目标:我想为每个方面的平均值画一条线。

我目前已经为所有方面的平均值绘制了一条线:

ggplot(mexi_sf, aes(FOODEXP)) +
  geom_density(alpha = 0.1,fill="red",colour="red") +
 facet_wrap(~ADM1NAME)+xlim(0, 436)+ geom_vline(xintercept=227)+
ggsave("myplot.png")

注意:我知道 227 是 summary 函数的平均值。

Here's the data 可以导入:

mexi_sf<-read_sf( dsn = getwd()
           , layer = "MexicoCaseStudy"
           , stringsAsFactors = FALSE ) 

您可以通过按管理对数据进行分组来做到这一点。请注意,您的数据中缺少编码为 -9999 的值。首先重新编码,然后在计算每组均值时使用 na.rm

mexi_sf %>%
  select(ADM1NAME, FOODEXP) %>%
  mutate(FOODEXP = ifelse(FOODEXP == -9999, NA, FOODEXP)) %>%
  group_by(ADM1NAME) %>%
  mutate(MEANEXP = mean(FOODEXP, na.rm = T)) -> mexi_sf


ggplot(mexi_sf, aes(FOODEXP)) +
  geom_density(alpha = 0.1,fill="red",colour="red") +
  facet_wrap(~ADM1NAME) + xlim(0, 436) + geom_vline(aes(xintercept=MEANEXP))+
  ggsave("myplot.png")