Борьба с линейным сюжетом (ggplot) - PullRequest
0 голосов
/ 31 августа 2018

У меня есть следующие (пример) данные:

testdata <- data.frame(theft=sample(size=100, c("yes", "no"), replace=T),
                   assault=sample(size=100, c("yes", "no"), replace=T),
                   robbery=sample(size=100, c("yes", "no"), replace=T),
                   agegrp=sample(size=100, c("10-20", "21-40", ">40"), replace=T))

theft <- table(testdata$theft, testdata$agegrp)[2,]
assault <- table(testdata$assault, testdata$agegrp)[2,]
robbery <- table(testdata$robbery, testdata$agegrp)[2,]

table <- rbind(theft, assault, robbery)

Моя цель - создать линейный сюжет (с ggplot), показывающий три разные линии (для каждого типа нарушения) по возрастным группам. Должен ли я сначала переставить их в нечто подобное?

offence  agegrp   count
/--------/--------/---------
theft    >40      22
theft    10-20    11
theft    21-40    22
...      ...      ...

Как я могу это сделать (не вручную)? И как мне тогда это построить?

ggplot(data, aes(x=agegrp, y=count, color=offence) + geom_line()

1 Ответ

0 голосов
/ 31 августа 2018

Вам не нужно создавать table набор данных, если вам удастся изменить исходный набор данных и затем построить график:

library(tidyverse)

testdata %>%
  group_by(agegrp) %>%                # for each age group
  summarise_all(~sum(.=="yes")) %>%   # count "yes" in all columns
  gather(offence,count,-agegrp) %>%   # reshape data
  mutate(agegrp = factor(agegrp, levels = c("10-20","21-40",">40"))) %>%  # specify order of levels (useful for plotting)
  ggplot(aes(x=agegrp, y=count, color=offence, group=offence)) + 
  geom_line()

enter image description here

...