Home > Software design >  Can we put several categories in a line graph?
Can we put several categories in a line graph?

Time:01-10

I'm working on a R project for training and I'm facing an issue. I tried to collect some data from the dataset 'relig_income' from tidyverse's package and to make a graph which represents the number of people in Catholic and Atheist according to their income range.

Indeed, I would like to make a line graph where in abscissa I have my column names ('<$10k', '$10-20k'... you can see them in my screenshot below) and in ordinate a range of numbers which accounts for their quantity (such as 20, 30...).

Nevertheless, I don't understand how I can make such a graphic because I don't see a way of putting several parameters (more than two) in a line graph.

Here my dataset

I tried vectors to add multiple data in my line graph, like this :

columnames = colnames(relig_income)[2:9]
relig_income %>% filter(religion == "Catholic" | religion == "Atheist") %>%
  ggplot(aes(x = columnames, y = c(relig_income$`<$10k`, relig_income$`$10-20k`, relig_income$`$20-30k`, relig_income$`$30-40k`)))   geom_line()
         
         

But it doesn't work (my code is weird so I can understand why, but I don't find another solution)

If somebody would have an idea, it would be a pleasure, thanks!

CodePudding user response:

How about something like this:

library(tidyverse)

relig_income %>% 
  filter(religion %in% c("Catholic", "Atheist")) %>% 
  pivot_longer(-religion, names_to="income_cat", values_to="size") %>% 
  filter(income_cat != "Don't know/refused") %>% 
  ggplot(aes(x=as.numeric(as.factor(income_cat)), y=size, colour=religion))   
  geom_line()   
  scale_x_continuous(breaks=1:9, labels=colnames(relig_income)[2:10])   
  labs(x="Income Category", y="Size")

Created on 2023-01-10 by the reprex package (v2.0.1)

  • Related