Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we put several categories in a line graph?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading