问题
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