使用ggplot绘制多列的时间序列

时间:2017-01-29 22:17:33

标签: r ggplot2 time-series

我有一个数据框,其中包含一列时间序列数据和9个其他具有每次信号强度值的变量,见下文:

    head(RTWP_Columns)
    Period.Start.Time DU0362U09A3 DU0362U09B3 DU0362U09C3 DU0362U21A1 DU0362U21A2 DU0362U21B1 DU0362U21B2 DU0362U21C1
1 01.16.2017 00:00:00     -104.54     -106.43     -104.40     -104.48     -103.04     -104.50     -103.58     -104.10
2 01.16.2017 00:15:00     -104.98     -106.49     -104.48     -104.47     -103.40     -104.50     -103.81     -104.22
3 01.16.2017 00:30:00     -105.34     -106.45     -104.50     -104.50     -103.23     -104.50     -104.01     -104.26
4 01.16.2017 00:45:00     -105.30     -106.48     -104.48     -104.50     -103.38     -104.41     -104.10     -104.32
5 01.16.2017 01:00:00     -104.99     -106.49     -104.50     -104.50     -103.44     -104.50     -104.36     -104.24
6 01.16.2017 01:15:00     -105.33     -106.49     -104.49     -104.50     -103.82     -104.50     -104.39     -104.39
  DU0362U21C2
1      -97.48
2      -99.18
3     -101.04
4     -101.76
5     -101.75
6     -101.97

我希望将每个变量绘制为单个图形中的一条线,并根据它们的变量名称对它们进行着色。

使用mill plot()和qplot()的运行绘图是很好的但是当涉及到美学时我很难,因为我是新手R用户。

如何绘制数据框,使时间在X轴上,我的列显示为单独的行?既然我的时间是类型因素,这是我悲伤的原因吗?我已经为我的时间创建了一个单独的posixct但我无法在ggplot中绘制这个。

以下是我的数据框的结构:

   str(RTWP_Columns)
'data.frame':   672 obs. of  10 variables:
 $ Period.Start.Time: Factor w/ 672 levels "01.16.2017 00:00:00",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ DU0362U09A3      : num  -105 -105 -105 -105 -105 ...
 $ DU0362U09B3      : num  -106 -106 -106 -106 -106 ...
 $ DU0362U09C3      : num  -104 -104 -104 -104 -104 ...
 $ DU0362U21A1      : num  -104 -104 -104 -104 -104 ...
 $ DU0362U21A2      : num  -103 -103 -103 -103 -103 ...
 $ DU0362U21B1      : num  -104 -104 -104 -104 -104 ...
 $ DU0362U21B2      : num  -104 -104 -104 -104 -104 ...
 $ DU0362U21C1      : num  -104 -104 -104 -104 -104 ...
 $ DU0362U21C2      : num  -97.5 -99.2 -101 -101.8 -101.8 ...

我使用了以下绘图功能但我无法将其转换为ggplot等效功能:

plot(times,RTWP_Columns$DU0362U09A3,
       type = "l",
       lwd=2,col="red",
       xlab = "Time",
       ylab = "RTWP (dBm)",
       main = "RTWP Plot for DU0362")
lines(times,RTWP_Columns$DU0362U09B3, col="green",lwd=2)
lines(times,RTWP_Columns$DU0362U09C3, col="blue",lwd=2)
lines(times,RTWP_Columns$DU0362U21A1, col="orange",lwd=2)
lines(times,RTWP_Columns$DU0362U21A2, col="purple",lwd=2)
lines(times,RTWP_Columns$DU0362U21B1, col="black",lwd=2)
lines(times,RTWP_Columns$DU0362U21B2, col="cyan",lwd=2)
lines(times,RTWP_Columns$DU0362U21C1, col="yellow",lwd=2)
lines(times,RTWP_Columns$DU0362U21C2, col="pink",lwd=2)

其中时间是我的posixct等效于RTWP_Columns中的period.start.time。

如果你能指向正确的方向,我将非常感激。

1 个答案:

答案 0 :(得分:3)

像这样的东西

library(ggplot2)
library(reshape2)
meltdf <- melt(df,id="Time")
ggplot(meltdf,aes(x=Time,y=value,colour=variable,group=variable)) + geom_line()

查看详情Plotting multiple time-series in ggplot

相关问题