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

梦想与她 提交于 2020-01-04 09:59:02

问题


Aim: I would like to draw a line down the mean for EACH individual facet.

I currently have plotted a line for the mean of all facets:

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")

Note: I know 227 is the mean from the summary function.

Here's the data that can be imported with:

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

回答1:


You can do that by grouping the data by administration. Note that you have missing values coded as -9999 in your data. Recode them first, then use na.rm when compting the means per group.

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")



来源:https://stackoverflow.com/questions/49541295/drawing-a-line-down-the-centre-mean-of-the-density-plots-for-each-facet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!