2015-08-14 243 views
-1

如何使用此数据集将图例添加到我的绘图中? 我想将所有变量绘制在同一个图中,并按名称标识线条。在ggplot2中添加绘图图例

Data   NO2   SO2    O3 
    2004-01-01 24.49864 2.756818 30.17857 
2 2004-01-02 33.40000 3.912609 22.45514 
3 2004-01-03 27.55435 5.654783 24.33342 
4 2004-01-04 24.87391 8.910000 30.64569 
5 2004-01-05 41.96348 10.893478 44.92825 
6 2004-01-06 48.80913 13.417391 44.91305 
7 2004-01-07 49.10217 16.808696 28.34968 
8 2004-01-08 49.14217 26.273913 16.61955 
9 2004-01-09 34.52261 8.438261 17.80235 
10 2004-01-10 45.33087 7.955217 36.34493 
+0

此复制必须计算器 –

+3

http://stackoverflow.com/questions/3777174/plotting-two-variables-as-lines发布-using-ggplot2-on-the-the-graph – user295691

+2

简而言之,您必须在'NO2'' geom_line'的美学中指定'color =“NO2”',对其他人也是如此,或者使用'reshape2' /'tidyr'首先融化数据 – user295691

回答

1

您可以使用gathertidyr绘制之前,你的数据帧重塑为长格式。

library(tidyr) 
library(ggplot2) 

# reshape to long format 
datL <- gather(dat, Var, value, -Data) 

# plot 
ggplot(datL, aes(x = Data, y = value, colour = Var, group = Var)) + 
    geom_line() 

在这里,dat是您的数据框的名称。

enter image description here

0
library(reshape2) 
library(ggplot2) 

s <- 
"Date   NO2   SO2    O3 
2004-01-01 24.49864 2.756818 30.17857 
2004-01-02 33.40000 3.912609 22.45514 
2004-01-03 27.55435 5.654783 24.33342 
2004-01-04 24.87391 8.910000 30.64569 
2004-01-05 41.96348 10.893478 44.92825 
2004-01-06 48.80913 13.417391 44.91305 
2004-01-07 49.10217 16.808696 28.34968 
2004-01-08 49.14217 26.273913 16.61955 
2004-01-09 34.52261 8.438261 17.80235 
2004-01-10 45.33087 7.955217 36.34493 
" 

df <- read.delim(textConnection(s), sep="") 
df$Date <- as.Date(df$Date, "%Y-%m-%d") 
df <- melt(df, id.vars="Date") 
ggplot(df, aes(Date, value, col=variable)) + 
    geom_line() 

这个问题是来自plot multiple columns on the same graph in Renter image description here