沿着EACH小平面的密度图的中心平均值绘制一条线 [英] Drawing a line down the centre mean of the density plots for EACH facet

查看:58
本文介绍了沿着EACH小平面的密度图的中心平均值绘制一条线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:我想在每个方面的均值下画一条线.

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

  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 函数的平均值.

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 ) 

解决方案

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

这篇关于沿着EACH小平面的密度图的中心平均值绘制一条线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆