如何使用ggplot2绘制时间间隔数据

时间:2022-08-10 02:55:42

I have a data.frame like this:

我有一个像这样的data.frame:

library(ggplot2)
library(reshape2)    
tasks <- c("Review literature", "Mung data")
    dfr <- data.frame(
      name        = factor(tasks, levels = tasks),
      start.date  = c("24/08/2010 01:00:01", "24/08/2010 01:00:10", "01/11/2010 01:30:00", "01/11/2010 02:00:00"),
      end.date    = c("24/08/2010 02:00:00", "24/08/2010 03:00:00", "01/11/2010 02:00:00", "01/11/2010 04:00:00")
    )
    mdfr <- melt(dfr, measure.vars = c("start.date", "end.date"))

I would like to plot this data using ggplot2 so that different dates are on different facets and only time portion is show on x-axis? I tried something like:

我想使用ggplot2绘制这些数据,以便不同的日期在不同的方面,只有时间部分显示在x轴上?我试过类似的东西:

ggplot(mdfr, aes(as.Date(value, "%H/%M/%S"), name)) + 
   geom_line(size = 6) +
   xlab("") + ylab("") +
   theme_bw() + facet_wrap(~as.Date(value, "%d/%m/%Y"))

Error in layout_base(data, vars, drop = drop) : 
  At least one layer must contain all variables used for facetting

1 个解决方案

#1


4  

Added to your melted data frame two new columns value2 and date. value2 is POSIXct class of your times and date column contains just date part of your original value and converted to factor to use for faceting.

添加到您的融化数据框两个新列value2和日期。 value2是您的时间的POSIXct类,日期列仅包含原始值的日期部分,并转换为用于分面的因子。

mdfr$value2<-as.POSIXct(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S"))
mdfr$date<-as.factor(as.Date(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S")))

Now you can use new value2 as x and date for facetting. I used facet_grid() with scales="free_x" and space="free_x" to get evenly spaced time intervals in both facets.

现在,您可以使用新值2作为x和日期进行构面。我使用了scale =“free_x”和space =“free_x”的facet_grid()来获得两个方面的均匀间隔时间间隔。

ggplot(mdfr, aes(value2, name)) + 
  geom_line(size = 6) +
  xlab("") + ylab("") +
  theme_bw() + facet_grid(~date,scales="free_x",space="free_x")

如何使用ggplot2绘制时间间隔数据

#1


4  

Added to your melted data frame two new columns value2 and date. value2 is POSIXct class of your times and date column contains just date part of your original value and converted to factor to use for faceting.

添加到您的融化数据框两个新列value2和日期。 value2是您的时间的POSIXct类,日期列仅包含原始值的日期部分,并转换为用于分面的因子。

mdfr$value2<-as.POSIXct(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S"))
mdfr$date<-as.factor(as.Date(strptime(mdfr$value, "%d/%m/%Y %H:%M:%S")))

Now you can use new value2 as x and date for facetting. I used facet_grid() with scales="free_x" and space="free_x" to get evenly spaced time intervals in both facets.

现在,您可以使用新值2作为x和日期进行构面。我使用了scale =“free_x”和space =“free_x”的facet_grid()来获得两个方面的均匀间隔时间间隔。

ggplot(mdfr, aes(value2, name)) + 
  geom_line(size = 6) +
  xlab("") + ylab("") +
  theme_bw() + facet_grid(~date,scales="free_x",space="free_x")

如何使用ggplot2绘制时间间隔数据