绘图图表两条线,两个刻度,两个y轴和底部的额外数据,带有R和绘图

时间:2014-02-19 19:36:47

标签: r charts plot lines

我想画这个:

enter image description here

我有这个数据集:

datetime,temperature,humidity,dpv
"2014-02-15 00:00:00",67.2,13.6,"red"
"2014-02-15 00:15:00",63.4,13.8,"yellow"
"2014-02-15 00:30:00",61.2,14.2,"green"
"2014-02-15 00:45:00",60.4,14.5,"green"

其中dpv是底部颜色的值。

需要混合秤并将湿度放在右侧轴上。

这是获取数据的代码:

datos_tem$datetime <- as.POSIXct(datos_tem$datetime)
datos_tem$temperature <- as.numeric(datos_tem$temperature)
datos_tem$humidity <- as.numeric(datos_tem$humidity)

但我不知道用PLOT(不是ggplot2)库做。

提前致谢。

2 个答案:

答案 0 :(得分:0)

建议使用这样的情节。在您的示例绘图的情况下,眼睛被绘制到2条线交叉的点,但这一点是由于任意比例选择而不是任何有意义的。如果您将温度范围更改为仅更改为14而不是20,则考虑图中的更改,然后交叉点将位于不同的位置。这个情节吸引人注意一个毫无意义的特征,而不是强调兴趣的差异。

最好是使用layoutpar(mfrow=c(2,1))将2个图堆叠在一起,这样可以看到相互增加,但没有交叉点,哪个比例与哪个数据相关完全清楚。

如果你仍然坚持下层情节,那么请查看plotrix包中的twoord.plot或TeachingDemos包中的updateusr(结合plotlines)。

答案 1 :(得分:0)

不完全相同但很相似:
enter image description here

代码:

datos_tem <- 
  read.csv(text=
             'datetime,temperature,humidity,dpv
           "2014-02-15 00:00:00",67.2,13.6,"red"
           "2014-02-15 00:15:00",63.4,13.8,"yellow"
           "2014-02-15 00:30:00",61.2,14.2,"green"
           "2014-02-15 00:45:00",60.4,14.5,"green"')

datos_tem$datetime <- as.POSIXct(datos_tem$datetime)
datos_tem$temperature <- as.numeric(datos_tem$temperature)
datos_tem$humidity <- as.numeric(datos_tem$humidity)
datos_tem$dpv <- as.character(datos_tem$dpv)

par(mar=c(5,4,4,5)+0.1)
# add temperature
plot(datos_tem$datetime,datos_tem$temperature,typ='b',col='red',
     ylab='Temperature',xlab='Time')

# add humidity
par(new=T)
plot(datos_tem$datetime,datos_tem$humidity,type='b', 
     col='blue',xaxt='n',yaxt='n',xlab='',ylab='')
axis(4)
mtext(side=4,text='Humidity',line=3)

# add colored bars
par(new=T)

xToler <- min(diff(datos_tem$datetime)) / 2
yToler <- (min(datos_tem$humidity) - par('usr')[3]) / 2

enc <- rle(datos_tem$dpv)

idx <- 1
for(i in 1:length(enc$lengths)){
  start <- datos_tem$datetime[idx] - xToler
  end <- datos_tem$datetime[idx + enc$lengths[i] - 1] + xToler
  rect(xleft=start,xright=end,
       ybottom=par('usr')[3],ytop=par('usr')[3]+yToler,col=enc$values[i])
  idx <- idx + enc$lengths[i]
}

注意:

代码非常通用,即它会根据原始“datos_tem”data.frame中的数据自动计算位置。