使用值

时间:2018-01-05 16:28:26

标签: r plot

我使用具有开始日期的不同传感器,如果它们在今天之前停止工作,则使用结束日期。不同的传感器给我不同的分辨率("值")。

我的数据框如下所示:

df <- structure(list(Start_date = structure(c(1L, 6L, 12L, 5L, 3L, 
2L, 11L, 13L, 10L, 9L, 4L, 7L, 8L), .Label = c("01.01.1990", 
"05.11.1991", "15.10.1991", "15.10.1993", "16.04.1991", "18.03.1990", 
"18.12.1993", "18.12.1994", "24.09.1992", "25.03.1992", "28.12.1991", 
"29.01.1991", "29.01.1992"), class = "factor"), End_date = structure(c(1L, 
6L, 3L, 5L, 1L, 7L, 10L, 8L, 2L, 11L, 9L, 4L, 1L), .Label = c("", 
"01.01.1995", "01.07.1994", "01.08.1994", "01.12.1992", "05.06.1992", 
"07.11.1994", "21.09.1995", "22.01.1995", "29.03.1995", "29.06.1994"
), class = "factor"), value1 = c(NA, NA, NA, NA, NA, 2, 1.2, 
NA, NA, NA, NA, NA, NA), value2 = c(NA, NA, NA, 7, NA, NA, 5.8, 
6, 7, 0.5, NA, NA, NA), value3 = c(20L, 15L, 10L, 15L, 20L, NA, 
20L, 15L, 20L, 20L, 20L, 10L, NA)), .Names = c("Start_date", 
"End_date", "value1", "value2", "value3"), class = "data.frame", row.names = c(NA, 
-13L))

我想在这样的图中绘制信息: enter image description here

我完全迷失在哪里开始。当我搜索样本数字时,我甚至不知道该寻找什么。

如何使用特定值绘制传感器的工作周期?

2 个答案:

答案 0 :(得分:3)

# Load libraries
library(magrittr)
library(ggplot2)
library(dplyr)
library(lubridate)
library(tidyr)

# Convert dates into correct format
# Convert from wide to long format
# Remove rows with NAs in the value column
# Add end point to open ended intervals
df %<>% 
  mutate(Start_date = as.Date(Start_date, format = "%d.%m.%Y"),
         End_date = as.Date(End_date, format = "%d.%m.%Y")) %>% 
  gather(variable, value, -Start_date, -End_date) %>% 
  filter(!is.na(value)) %>% 
  mutate(End_date = if_else(is.na(End_date), max(End_date, na.rm = TRUE), End_date))


# Plot results
ggplot(df) + geom_segment(aes(x = Start_date, 
                              xend = End_date, 
                              y = value, 
                              yend = value, 
                              colour = variable), size = 2)

enter image description here

答案 1 :(得分:0)

这是基础r的东西

f<-function(x) as.POSIXct(x,"UTC","%d.%m.%Y")
df$Start_date<-f(df$Start_date)
df$End_date<-f(df$End_date)
df$End_date[is.na(df$End_date)]<-Sys.Date()
x<-c(df[[1]],df[[2]])
dts<-as.Date(seq(f(min(x)),f(max(x)),"year"))
h<-!is.na(df[,3:5])
j<-apply(h,1,sum)
j<-unlist(sapply(1:13,function(x) rep(x,j[x])))
col<-do.call(c,apply(h,1,function(x) which(x %in% T)))
plot(x,1:26,type="n",las=2,ylim=c(1,20),xaxs="r",ylab="",xlab="")
for(i in 1:18) 
lines(df[j[i],1:2],rep(i,2),las=2,type="l",lwd=5,col=rainbow(3)[col[i]])
legend("topright",legend = paste("Value",1:3),bty="n",fill=rainbow(3))

enter image description here