在ggplot2中添加图例

时间:2015-08-14 19:42:53

标签: r 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

2 个答案:

答案 0 :(得分:1)

在绘图之前,您可以使用gather中的tidyr将数据框重新整形为长格式。

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

答案 1 :(得分: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 R enter image description here

重复