Miffy  Xiao
Miffy Xiao

Reputation: 1

how to plot two lines on the same graph?

Here is my dataframe. I just want to plot y1 and y2 on the same graph to compare two values. Anyone knows how to do it? It should be a line plot. Thank you very much!

> cduck
            x    y1    y2
1  2017-10-05  3.05  5.61
2  2017-10-07  0.77  2.95
3  2017-10-08  1.04  3.23
4  2017-10-10  4.06  3.95
5  2017-10-12  4.29  4.59
6  2017-10-14  0.49  0.77
7  2017-10-17 12.80  8.71
8  2017-10-19  3.12  7.18
9  2017-10-21  5.53  9.00
10 2017-10-22  3.42 10.00
11 2017-10-24  2.00  1.42
12 2017-10-26  1.90  3.05
13 2017-10-29  4.47 12.44
14 2017-10-31  2.43  3.83
15 2017-11-05  3.64  1.91

enter image description here

I did it in excel but i just want to know how to plot it in R!

Upvotes: 0

Views: 89

Answers (1)

Mako212
Mako212

Reputation: 7312

require(ggplot2)
require(reshape2)

First we need to transform to "long" format using reshape2::melt

df1 <- melt(df1, id.var="x")
df1$x <- as.Date(df1$x)

enter image description here

Then plot mapping color to the generated variable column in df1.

ggplot(df1, aes(x, value, color = variable)+
  geom_line()

Data:

df1 <- structure(list(x = structure(1:15, .Label = c("2017-10-05", "2017-10-07", 
"2017-10-08", "2017-10-10", "2017-10-12", "2017-10-14", "2017-10-17", 
"2017-10-19", "2017-10-21", "2017-10-22", "2017-10-24", "2017-10-26", 
"2017-10-29", "2017-10-31", "2017-11-05"), class = "factor"), 
    y1 = c(3.05, 0.77, 1.04, 4.06, 4.29, 0.49, 12.8, 3.12, 5.53, 
    3.42, 2, 1.9, 4.47, 2.43, 3.64), y2 = c(5.61, 2.95, 3.23, 
    3.95, 4.59, 0.77, 8.71, 7.18, 9, 10, 1.42, 3.05, 12.44, 3.83, 
    1.91)), .Names = c("x", "y1", "y2"), class = "data.frame", row.names = c("1", 
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", 
"14", "15"))

Upvotes: 3

Related Questions