Reputation: 627
I'm currently doing some plotting of temperature/time. I'm coloring the data points by the on/off status of the heater. When plotting at larger time scales, the points start to get melded together and the sine-like pattern of the points is obscured. This pattern is much clearer if I set type = 'l'
in the plot() call, but that doesn't allow me to color by heater status.
Is there a way to color parts of a line by an associated column value? Or alternatively, is there a way I could split the data and plot the line as a series of line segments, splitting the data by heater status that will scale with different time ranges?
Here is some example code
templog = data.frame(temp = c(0,1,2,3,4,4,3,2,1,0,0,1,2,3,4),
time = as.POSIXct(c('2019-02-10 00:00:05','2019-02-10 00:00:10','2019-02-10 00:00:15','2019-02-10 00:00:20','2019-02-10 00:00:25','2019-02-10 00:00:30','2019-02-10 00:00:35','2019-02-10 00:00:40','2019-02-10 00:00:45','2019-02-10 00:00:50','2019-02-10 00:00:50','2019-02-10 00:00:55','2019-02-10 00:01:00','2019-02-10 00:01:05','2019-02-10 00:1:10'), tz = 'GMT'),
heaterstatus = c('on','on','on','on','on','off','off','off','off','off','on','on','on','on','on'))
plot(templog$temp~templog$time, col = as.factor(templog$heaterstatus))
plot(temp~time, data = templog, col = as.factor(heaterstatus), type = 'l')
In the second plot() call, I'd like to have different sections of the line be colored differently. If that is not possible, I'd like a way of automating splitting the data and plotting different line segments by heaterstatus that will scale as I add new data to the log.
Thanks.
Upvotes: 0
Views: 484
Reputation: 51
This is possible, with the segments function.
for(i in 1:(length(templog$time)-1)){
segments(templog$time[i],
templog$temp[i],
templog$time[i+1],
templog$temp[i+1],
col=templog$heaterstatus[i])
}
Basically, you're iterating through each pair of points & draws a straight line in the specified color. Also, you can simplify your plot()
call-
plot(temp~time, data=templog, type='n')
would suffice.
Hope this helps :-)
Upvotes: 1