如何在R

时间:2017-08-09 16:33:02

标签: r plot ggplot2 time-series

我有以下表格的数据:

Date          Factor Value
10/1/2016 4:00  107 116
10/1/2016 4:00  109 69
10/1/2016 4:00  127 85
10/1/2016 4:00  129 94
10/1/2016 4:00  131 85
10/1/2016 12:00 107 116
10/1/2016 12:00 109 97
10/1/2016 12:00 127 89
10/1/2016 12:00 129 107
10/1/2016 12:00 131 89
10/1/2016 20:00 107 96
10/1/2016 20:00 109 85
10/1/2016 20:00 127 110
10/1/2016 20:00 129 103
10/1/2016 20:00 131 100
10/2/2016 4:00  107 105
10/2/2016 4:00  109 71
10/2/2016 4:00  127 110
10/2/2016 4:00  129 69
10/2/2016 4:00  131 55
10/2/2016 12:00 107 69
10/2/2016 12:00 109 108

总共有32个因素。对于每个日期和时间,可以有多个因素和相关值。 我希望比较每个因素的值的时间序列。最好的方法是什么?

我使用了以下两种方法,但它们没有产生令人满意的结果:

方法1:

ggplot(data = df, aes(x = as.POSIXct(df$Date), y = df$Value)) + geom_line() + geom_point() + facet_wrap(~df$Factor)

情节:facet_wrap figure

方法2:

      plot(as.POSIXct(df$Date), df$Value, col='red', pch=12)

情节:separate plots for factors

所有因素在所有时间点都没有数据。我想要一个共同的时间轴,多个数字显示沿Y的不同数字的数据(类似于第二个数字,但更好的呈现)。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

在最后的注释中使用DF重复显示直接标记包。

library(directlabels)
library(ggplot2)

DF$Date <- as.POSIXct(DF$Date, format = "%m/%d/%Y %H:%M")

ggplot(DF, aes(Date, Value, group = Factor)) + 
  geom_line() +
  geom_point() +
  geom_dl(aes(label = Factor), 
    method = list(dl.combine("first.points", "last.points"), cex = 0.7)) 

screenshot

注意:可重复形式的输入DF为:

Lines <- '
"","Date","Factor","Value"
"1","10/1/2016 4:00",107,116
"2","10/1/2016 4:00",109,69
"3","10/1/2016 4:00",127,85
"4","10/1/2016 4:00",129,94
"5","10/1/2016 4:00",131,85
"6","10/1/2016 12:00",107,116
"7","10/1/2016 12:00",109,97
"8","10/1/2016 12:00",127,89
"9","10/1/2016 12:00",129,107
"10","10/1/2016 12:00",131,89
"11","10/1/2016 20:00",107,96
"12","10/1/2016 20:00",109,85
"13","10/1/2016 20:00",127,110
"14","10/1/2016 20:00",129,103
"15","10/1/2016 20:00",131,100
"16","10/2/2016 4:00",107,105
"17","10/2/2016 4:00",109,71
"18","10/2/2016 4:00",127,110
"19","10/2/2016 4:00",129,69
"20","10/2/2016 4:00",131,55
"21","10/2/2016 12:00",107,69
"22","10/2/2016 12:00",109,108'
DF <- read.csv(text = Lines)