Rahul H
Rahul H

Reputation: 45

ggplot showing a trend with more than 1 variables across y axis

I have a dataframe df where I need to see the comparison of the trend between weeks

df
Col Mon Tue Wed
 1  47  164 163
 2  110 168 5
 3  31  146 109
 4  72  140 170
 5  129 185 37
 6  41  77  96
 7  85  26  41
 8  123 15  188
 9  14  23  163
 10 152 116 82
 11 118 101 5

Right now I can only plot 2 variables like below. But I need to see for Tuesday and Wednesday as well

ggplot(data=df,aes(x=Col,y=Mon))+geom_line()

Upvotes: 0

Views: 38

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388817

The standard way would be to get the data in long format and then plot

library(tidyverse)

df %>%
  gather(key, value, -Col) %>%
  ggplot() + aes(factor(Col), value, col = key, group = key) + geom_line()

enter image description here

Upvotes: 1

Chris Littler
Chris Littler

Reputation: 191

You can either add a

geom_line(aes(x = Col, y = Mon), col = 1)

for each day, or you would need to restructure your data frame using a function like gather so your new columns are col, day, value. Without reformatting the data, your result would be

ggplot(data=df)+geom_line(aes(x=Col,y=Mon), col = 1) + geom_line(aes(x=Col,y=Tue), col = 2) + geom_line(aes(x=Col,y=Wed), col = 3)

with a restructure it would be

ggplot(data=df)+geom_line(aes(x=Col,y=Val, col = Day))

Upvotes: 1

Related Questions