如何在R中绘制具有有限范围x轴的时间数据

时间:2017-05-10 03:37:24

标签: r plot

d=read.table(text="in_type, in_time, out_type, out_time, d2d, e2e
    R1,14:56:04.434285,R2,14:56:04.434534,152,249
    R1,14:56:04.522163,R2,14:56:04.522325,113,162
    R1,14:56:04.606073,R2,14:56:04.606228,112,155
    R1,14:56:04.824225,R2,14:56:04.824391,116,166
    R1,14:56:06.621347,R2,14:56:06.621511,116,164
    R1,14:56:37.677250,R2,14:56:37.677452,135,202
    R1,14:56:38.897656,R2,14:56:38.897839,123,183
    R1,14:56:50.361073,R2,14:56:50.361268,127,195
    R1,14:59:09.768824,R3,14:59:09.769006,138,182
", sep=',', header=T)
d=d[order(d$in_time),]
d$in_s = strptime(substr(d$in_time,1,8),"%H:%M:%S")
plot(d$in_s,d$d2d)

plot(d$in_s,d$d2d, xlim=c('14:56:06','14:56:37'))
Error in plot.window(...) : invalid 'xlim' value

class(d$in_s) # will get POSIXlt
plot(d$in_s,d$d2d, xlim=as.POSIXlt(c('14:56:06','14:56:37', format="%H:%M:%S"))
Error in plot.window(...) : invalid 'xlim' value

2 个答案:

答案 0 :(得分:1)

您可以使用ggplot2例如:

library(ggplot2)
library(scales)
ggplot(d) + geom_line(aes(x = in_s,y = d2d)) + 
  scale_x_datetime(limits = as.POSIXct(c("14:56:06", "14:56:37"), format = "%H:%M:%S"), breaks=date_breaks("1 secs"), labels=date_format("%H:%M:%S"))+
theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

答案 1 :(得分:1)

首先,你需要一个

  

头= T

阅读您的数据。对于

  

XLIM

它不能直接接受字符串。你需要格式化它。以下代码适合您

 d=read.table(text="in_type, in_time, out_type, out_time, d2d, e2e
                 R1,14:56:04.434285,R2,14:56:04.434534,152,249
                 R1,14:56:04.522163,R2,14:56:04.522325,113,162
                 R1,14:56:04.606073,R2,14:56:04.606228,112,155
                 R1,14:56:04.824225,R2,14:56:04.824391,116,166
                 R1,14:56:06.621347,R2,14:56:06.621511,116,164
                 R1,14:56:37.677250,R2,14:56:37.677452,135,202
                 R1,14:56:38.897656,R2,14:56:38.897839,123,183
                 R1,14:56:50.361073,R2,14:56:50.361268,127,195
                 R1,14:59:09.768824,R3,14:59:09.769006,138,182", sep=',',header=T)
    d=d[order(d$in_time),]
    d$in_s = strptime(substr(d$in_time,1,8),"%H:%M:%S")

    plot(d$in_s,d$d2d, xlim=as.POSIXct(c("14:56:06", "14:56:37"), format = "%H:%M:%S") )