如何在同一图表上绘制两条线?

时间:2017-11-19 20:47:48

标签: r

这是我的数据框架。我只想在同一图表上绘制y1和y2来比较两个值。谁知道怎么做?它应该是一个线图。非常感谢你!

> 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

我是在excel中做到的,但我只是想知道如何在R中绘制它!

1 个答案:

答案 0 :(得分:3)

require(ggplot2)
require(reshape2)

首先,我们需要使用reshape2::melt

转换为“长”格式
df1 <- melt(df1, id.var="x")
df1$x <- as.Date(df1$x)

enter image description here

然后将color映射到variable中生成的df1列。

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

数据:

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"))
相关问题