Overlaying line graph with barplot in ggplot2

2019-06-09 16:40发布

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

enter image description here

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.

标签: r ggplot2
1条回答
爷、活的狠高调
2楼-- · 2019-06-09 16:59

using data.table for data-manipulation and lukeA's comment:

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

Result: enter image description here

查看更多
登录 后发表回答