在ggplot2中用条形图覆盖折线图

Overlaying line graph with barplot in ggplot2

提供的 the following 数据框(见下文)是从调查问卷中取出的,询问来自不同社区的人们的感知安全性,我设法创建了一个条形图,显示每个人的感知安全性和分组结果街区:

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 的第一份工作,我不知道如何使用数据框计算平均值,然后将其覆盖在之前的条形图中。

使用 data.table 进行数据处理和 lukeA 的评论:

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

结果: