如何在另一个df的情节中显示来自一个df的评论?

时间:2018-02-14 17:03:02

标签: r ggplot2

我有2个像这样的数据框

Timestamp <- c("2018-01-25 01:03:46","2018-01-25 10:09:36","2018-01-25 11:28:47")
Type <- c("Measurement","Measurement","Measurement")
Comment <- c("Positive","Negative","Positive")
df1 <- data.frame(Timestamp,Type,Comment) 
df1$Timestamp <- as.POSIXct(df1$Timestamp,format="%Y-%m-%d %H:%M:%S")

Timestamp <- c("2018-01-25 00:03:46","2018-01-25 01:03:46","2018-01-25 08:28:47","2018-01-25 09:09:36","2018-01-25 10:28:47",
               "2018-01-25 11:03:46","2018-01-25 12:09:36","2018-01-25 14:28:47","2018-01-25 17:09:36","2018-01-25 18:28:47")
Type <- c("Measurement","Measurement","Measurement","Measurement","Measurement",
          "Measurement","Measurement","Measurement","Measurement","Measurement")
Length <- c(35,39,38,33,29,31,34,36,33,37)
df2 <- data.frame(Timestamp,Type,Length) 
df2$Timestamp <- as.POSIXct(df2$Timestamp,format="%Y-%m-%d %H:%M:%S")

我正在尝试用&#34;评论&#34;来绘制df2。 df1的列重叠在图中。 当我合并df1&amp;像这样的df2

library(dplyr)
df_join <- left_join(df2, df1, by=c("Timestamp","Type"),all.x=T)

我得到了

             Timestamp        Type Length  Comment
   2018-01-25 00:03:46 Measurement     35     <NA>
   2018-01-25 01:03:46 Measurement     39 Positive
   2018-01-25 08:28:47 Measurement     38     <NA>
   2018-01-25 09:09:36 Measurement     33     <NA>
   2018-01-25 10:28:47 Measurement     29     <NA>
   2018-01-25 11:03:46 Measurement     31     <NA>
   2018-01-25 12:09:36 Measurement     34     <NA>
   2018-01-25 14:28:47 Measurement     36     <NA>
   2018-01-25 17:09:36 Measurement     33     <NA>
   2018-01-25 18:28:47 Measurement     37     <NA>

因此,当我绘制它时,只有&#34;肯定&#34;评论显示在图中。

library(ggplot2)
library(ggrepel)
library(scales)
ggplot(data = df_join,aes(x=Timestamp,y=Length)) + 
  geom_line(aes(y = Length, colour = "Length"),size = 0.5) +                      
  geom_point(alpha=0.6, position=position_jitter(w=0.05, h=0.0), size=1) +
  geom_text_repel(aes(Timestamp, Length, label = Comment)) +
  scale_x_datetime(breaks = date_breaks("2 hours"),labels = date_format("%m/%d %H:%M"))  + 
  theme(legend.position="none")

我想在df1的同一个df2中获得df1中的其他注释(带有时间戳)。有没有比合并2个数据帧更好的方法呢?

0 个答案:

没有答案