-2

I have a data set in which, for each day in the work week (Monday - Friday), I have a value that belongs to a category. In table form, it looks like this:

cat | day | value
 A  |  0  | 1
 A  |  1  | 0
 A  |  2  | 2
 A  |  3  | 1
 A  |  4  | 3
 B  |  0  | 0
 ...and so on...

Every category has a value for days 0-4.

What I would like to do is plot each category as a separate line (on the same plot), where the x values are the days, and the y values are the values for each day. How can I accomplish this in R?

kjwill555
  • 25
  • 6
  • `library(ggplot2); ggplot(dat, aes(day, value, colour=cat)) + geom_line() + geom_point()`, where `dat` is your data frame. – eipi10 Aug 31 '17 at 23:00

1 Answers1

0

This is very straightforward to do with the ggplot2 library as mentioned in the comments, and you can do this by setting an aesthetic like colour on your category variable but in order to have distinct lines for each of your categories without specifying other aesthetics, you need to use the group aesthetic. There is extensive documentation here.

library(ggplot2)

dat <- data_frame(category = c("A","A","A","A","B","B","B","B"), 
              day = c(1,2,3,4,1,2,3,4), 
              value = c(1,0,2,1,3,2,1,3))

ggplot(dat, aes(x = day, y = value, colour = category, group = category)) + geom_line()

image

Furthermore, this is probably a duplicate of Plot multiple lines (data series) each with unique color in R.

dshkol
  • 1,208
  • 7
  • 23