Juan Lozano
Juan Lozano

Reputation: 667

How to create multiple line chart in r

I have a data frame in this structure

Date          x1      x2      x3    x4
1/2/2018  500000   10000     10     80000 
1/3/2018  600000   15000     13     70000
1/4/2018  300000   8000      7      40000

How can I create a ggplot line chart with with the 4 x variables in the same chart, also since x3 is so little in respect with the other values it might get lost in the graph is there a trick to deal with this?

Thanks.

Upvotes: 2

Views: 763

Answers (2)

Hafizah Ilma
Hafizah Ilma

Reputation: 11

data <- airquality %>%
    group_by(Month) %>%
    summarise(mean_Ozone = mean(Ozone, na.rm=TRUE),
             mean_Solar.R = mean(Solar.R, na.rm=TRUE),
             mean_Wind = mean(Wind),
             mean_Temp = mean(Temp))

data2 <- reshape2::melt(data, id.vars = "Month")
ggplot(data2, aes(x = Month, y = value, 
                 group = variable, colour = variable)) +geom_line() 

Upvotes: 1

Rui Barradas
Rui Barradas

Reputation: 76651

First, the dataset.

df1 <- read.table(text = "
Date          x1      x2      x3    x4
1/2/2018  500000   10000     10     80000 
1/3/2018  600000   15000     13     70000
1/4/2018  300000   8000      7      40000                  
", header = TRUE)
df1$Date <- as.Date(df1$Date, "%m/%d/%Y")

The following will plot the three lines using a log10 scale.

library(ggplot2)

long <- reshape2::melt(df1, id.vars = "Date")
ggplot(long, aes(x = Date, y = value, 
                 group = variable, colour = variable)) +
  geom_line() +
  scale_y_log10() 

enter image description here

Upvotes: 4

Related Questions