时间线条,带有基于时间序列值的颜色/填充(R ggplot) [英] Timeline bar with colour/fill based on time-series' value (R ggplot)
问题描述
我有一个时间序列数据框,定期读取压力读数。
时间压差
1 2014-09-09 09:12:29 1.6191598 0.00000000
2 2014 -09-09 09:12:28 3.0137784 -0.07668387
3 2014-09-09 09:12:27 1.1958183 0.58693260
4 2014-09-09 09:12:26 2.2803681 1.07774954
5 2014-09-09 09:12:25 -0.7614310 -0.17864232
6 2014-09-09 09:12:24 0.9914106 -0.70121973
我可以使用ggplot2轻松制作压力线图。但是在这条线下面,我想要有一个水平条,填充颜色取决于两个连续样本之间的压差(df字段 diff
)。
例如,在压差为零的情况下(即压力在两个连续采样之间没有变化),条块将是白色的。填充颜色会随着差分正向增加(比如说)红色而变深,而随着负向值增加,填充颜色会变成蓝色。
生成示例数据:
dfTimeSeries< - data.frame (时间= Sys.time() - seq(1:10),
压力= rnorm(10,1),
diff = c(0,diff(dfTimeSeries $压力)))
情节的第一部分
ggplot(data = dfTimeSeries)+
geom_line(aes(x = time,y = pressure))
我该如何编码横跨整个x轴(时间轴)的水平条,其填充颜色会根据 diff
我的df的字段为相应的时间戳?
我最终把 geom_rect
对象左右对齐,每个 diff
值的矩形。这里有一个基本的概念:
pre $ $ c $ ggplot(data = dfTimeSeries)+
geom_line(aes(x = time,y =压力))+
geom_rect(aes(xmax = time + .5,xmin = time-.5,ymax = -3,ymin = -2,fill = diff))
我需要调整颜色比例,将条纹放在不同的图表中,然后做一些更美观的排列等等。
I've got a time-series data frame with pressure readings taken at regular intervals.
time pressure diff
1 2014-09-09 09:12:29 1.6191598 0.00000000
2 2014-09-09 09:12:28 3.0137784 -0.07668387
3 2014-09-09 09:12:27 1.1958183 0.58693260
4 2014-09-09 09:12:26 2.2803681 1.07774954
5 2014-09-09 09:12:25 -0.7614310 -0.17864232
6 2014-09-09 09:12:24 0.9914106 -0.70121973
I can easily make a line plot of the pressure using ggplot2. But below this line plot, I'd like to have a horizontal bar where the fill colour depends on the pressure differential between two consecutive samples (df field diff
).
For example, the bar would be white at times where the pressure differential is zero (i.e. pressure has not changed bewteen two consecutive samples). The fill colour would go towards a deeper shade of (say) red as the differential increases positively, and blue as it increases in the negative values.
generate sample data:
dfTimeSeries <- data.frame(time = Sys.time()-seq(1:10),
pressure = rnorm(10,1),
diff = c(0,diff(dfTimeSeries$pressure)))
First part of the plot
ggplot(data = dfTimeSeries)+
geom_line(aes(x=time, y=pressure))
How can I code this horizontal bar that would span along the entire x (time) axis and whose fill colour would vary based on the on the diff
field of my df for the corresponding timestamp?
I ended up putting geom_rect
objects side-to-side, one rectangle for each value of diff
. Here's the basic concept:
ggplot(data = dfTimeSeries)+
geom_line(aes(x=time, y=pressure))+
geom_rect(aes(xmax=time+.5, xmin=time-.5,ymax=-3,ymin=-2, fill=diff))
I'd need to to adjust the colour scale, fit the bars in a different graph, and do a bit more cosmetic arrangmeents, etc.
这篇关于时间线条,带有基于时间序列值的颜色/填充(R ggplot)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!