Kelly
Kelly

Reputation: 145

Make line graph from frequency table in R

I have made a frequency table to look at the percentage of race categories across a 4 year period. Using the following code:

race <- table(crc$raceeth, crc$year)
perrace <- prop.table(race, 2)

I created a table that looks like this:

                      2014      2015      2016      2017      2018
  Other              0.1032609 0.1433232 0.1335762 0.1141788 0.1285297
  Latino             0.3913043 0.3339548 0.2173649 0.2321011 0.2434275
  non-hispanic black 0.3695652 0.3087858 0.3995143 0.4361254 0.4634859
  non-hispanic white 0.1358696 0.2139361 0.2495446 0.2175948 0.1645570

Now I want to create a line graph that has year on the x axis and lines for each race/ethnicity on the y, but I am not sure where to go from here

Upvotes: 1

Views: 1695

Answers (1)

Maurits Evers
Maurits Evers

Reputation: 50728

Here is a tidyverse approach:

library(tidyverse)
df %>%
    rownames_to_column("Group") %>%
    gather(x, y, -Group) %>%
    mutate(x = as.Date(gsub("X", "", x), format = "%Y")) %>%
    ggplot(aes(x, y, colour = Group)) +
    geom_line()

enter image description here


Sample data

df <- read.table(text =
    "                    2014      2015      2016      2017      2018
  'Other'              0.1032609 0.1433232 0.1335762 0.1141788 0.1285297
  'Latino'             0.3913043 0.3339548 0.2173649 0.2321011 0.2434275
  'non-hispanic black' 0.3695652 0.3087858 0.3995143 0.4361254 0.4634859
  'non-hispanic white' 0.1358696 0.2139361 0.2495446 0.2175948 0.1645570", header = T, row.names = 1);

Upvotes: 2

Related Questions