【问题标题】:R + ggplot: Order irregular Time Strings for PlotR + ggplot:为绘图订购不规则时间字符串
【发布时间】:2015-03-04 14:50:37
【问题描述】:

我有一个包含两列的数据框。第一个是数值,另一个是描述时间的字符串。时间格式看起来像 yyyy-mm-dd--hh-mm-ss-?????? (例如 2015-03-04--12-11-35-669696),我不知道最后 6 位数字是什么意思。例如

       y                        time
1  4.548 2014-08-11--09-07-44-202586
2  4.548 2014-08-11--09-07-54-442586
3  4.548 2014-08-11--09-08-04-522586
4  4.478 2014-08-11--09-08-14-762586
5  4.431 2014-08-11--09-08-24-522586
6  4.446 2014-08-11--09-08-34-922586
7  4.492 2014-08-11--09-08-44-522586
8  4.508 2014-08-11--09-08-54-442586
9  4.486 2014-08-11--09-09-04-202586
10 4.497 2014-08-11--09-09-14-442586
11 4.461 2014-08-11--09-09-24-202586

我想绘制它们

ggplot(df, aes(x=time, y=y)) + geom_line()

但我有一个问题,ggplot 不知道如何处理类字符的数据,尤其是我给定的时间格式。 我尝试使用包 {sfsmisc} 中的 AsciiToInt 将字符串转换为数值,但它为每个字符串重复一个整数列表(当然,每个字符一个数字)。 我还可以使用包 {gtools} 中的 mixedsort 对我的时间字符串进行排序,但我不知道如何将它应用于绘图(还要记住距离)。

另一个问题是我不希望每次字符串在 x 轴上都显示为刻度,因为我有大约 20k 行。也许我可以像this question 那样解决这个问题,但只要出现第一个问题,我就无法检查。

你能帮我在 x 轴上将这些数据与时间绘制成类似数字的值吗?

【问题讨论】:

    标签: r string time ggplot2 format


    【解决方案1】:

    我将您的数据加载为名为 time dat 的 .txt 文件。首先,我将您的数据转换为 POSIXct 类型。为了使图表更清晰以用于测试目的,我省略了 seconds 字段,如果您想添加它们,只需使用注释掉的行。

    library(ggplot2)
    timedat<-read.csv("~/Work/Timedat.csv")
    timedat
    str(timedat)
    > str(timedat)
    'data.frame':   11 obs. of  3 variables:
     $ X   : int  1 2 3 4 5 6 7 8 9 10 ...
     $ y   : num  4.55 4.55 4.55 4.48 4.43 ...
     $ time: Factor w/ 11 levels "2014-08-11--09-07-44-202586",..: 1 2 3 4 5 6 7 8 9 10 ...
    
    #timedat$time<-as.POSIXct(as.character(timedat$time),format = "%Y-%m-%d--%H-%M-%S")
    
    timedat$time<-as.POSIXct(as.character(timedat$time),format = "%Y-%m-%d--%H-%M")
    
    qplot(data=timedat,y=y,x=time)+theme_bw()
    
    > timedat
        X     y                        time
    1   1 4.548 2014-08-11--09-07-44-202586
    2   2 4.548 2014-08-11--09-07-54-442586
    3   3 4.548 2014-08-11--09-08-04-522586
    4   4 4.478 2014-08-11--09-08-14-762586
    5   5 4.431 2014-08-11--09-08-24-522586
    6   6 4.446 2014-08-11--09-08-34-922586
    7   7 4.492 2014-08-11--09-08-44-522586
    8   8 4.508 2014-08-11--09-08-54-442586
    9   9 4.486 2014-08-11--09-09-04-202586
    10 10 4.497 2014-08-11--09-09-14-442586
    11 11 4.461 2014-08-11--09-09-24-202586
    

    这会产生以下情节,其中日期排列得很好。

    【讨论】:

    • 当我还想添加秒时,我使用了format="%Y-%m-%d--%H-%M-%S,但刻度只显示分钟(45,00,15,30,45,...)。所以我用scale_x_datetime(breaks = date_breaks("30 sec"), labels=date_format("%Y-%m-%d %H:%M:%S")) 来解决这个问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 2019-02-16
    • 2017-08-26
    • 1970-01-01
    相关资源
    最近更新 更多