在ggplot2中用barplot叠加折线图 [英] Overlaying line graph with barplot in ggplot2

查看:1486
本文介绍了在ggplot2中用barplot叠加折线图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提供以下数据框(见下文),这是从一份调查问卷中询问有关来自不同社区的人的感知安全问题的,我设法创建了一个条形图,显示感知的安全性并将每个社区的结果分组:

Provided the following dataframe (see below) which was taken out of a questionnaire asking about perceived security to people from different neighborhoods, I have managed to create a bar plot which displays perceived security and groups results per each neighborhood:

questionnaire_raw = read.csv("https://www.dropbox.com/s/l647q2omffnwyrg/local.data.csv?dl=0")

ggplot(data = questionnaire_raw, 
       aes(x = factor(Seguridad.de.tu.barrio..de.día.), # We have to convert x values to categorical data
           y = (..count..)/sum(..count..)*100,
           fill = neighborhoods)) + 
  geom_bar(position="dodge") + 
  ggtitle("Seguridad de día") + 
  labs(x="Grado de seguridad", y="% encuestados", fill="Barrios")

我想用表示每个安全类别(1,2,3或4)在所有邻域中的平均值的线图覆盖这些结果(这是没有分组的结果),所以很容易知道某个特定的街区是否超过或低于所有街区的平均数。但是,由于这是我第一次使用R,因此我不知道如何用数据框计算这个平均值,然后将它覆盖在之前的barplot中。

I would like to overlay these results with a line graph representing the mean of each security category (1, 2, 3 or 4) in all neighborhoods (this is, without grouping results), so it is easy to know if a specific neighborhood is over or under the average of all neighborhoods. However, since it's my first job with R, I do not know how to calculate that mean with a dataframe and then overlay it in the previous barplot.

推荐答案

require(ggplot2)
require(data.table)
setDT(questionnaire_raw)
setnames(questionnaire_raw, c("Timestamp", "Barrios", "Grado"))

plot_data <- questionnaire_raw[,.N, by=.(Barrios,Grado)]
ggplot(plot_data, aes(x=factor(Grado), y = N, fill = Barrios)) +
  geom_bar(position="dodge", stat="identity") +
  stat_summary(fun.y=mean, geom = "line", mapping = aes(group = 1)) +
  ggtitle("Seguridad de día") + 
  labs(x="Grado de seguridad", y="% encuestados", fill="Barrios")

结果:

这篇关于在ggplot2中用barplot叠加折线图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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