R:熔化data.frame以在ggplot2中用于多个y值图

时间:2015-06-09 08:54:00

标签: r plot ggplot2 melt

我想针对时间变量绘制多个Y值。我没有完整的数据框,因为我没有收集所有的Y值。我相信在将数据框传递给ggplot2之前我需要先熔化数据框,但这似乎失败了,因为“id”列并不总是被填充。这就是我尝试过的,其中包含严重破坏的ggplot端:

    library("ggplot2")
    library("reshape2")

    #Example data
    Date=c("2015-06-09", "2015-06-09", "2015-06-09")
    Time=c("07:00:01",   "08:00:01",   "09:00:01")
    src=c(47420413232,   47519749372,  47571637056)
    dest=c(NA,           NA,           49738231808)
    df = data.frame(Date, Time, src, dest)

    # process into a real "time" type, throw away the previous types
    df$time =  as.POSIXlt(paste(df$Date, df$Time))
    df$Date = NULL
    df$Time = NULL

    # review df to check it's sane
    df

    # melt the data to transform it for plotting
    molten_space = melt(df, id.vars="time")

    # now look at molten_space for what I think goes wrong
    molten_space


    # doesn't work at all, but basically I want to plot both src(y-value) and dest(y-value) against time(x-value)

    ggplot(data=molten_space, aes(x=time, y=value, group="time")) + geom_line() + scale_y_continuous("Space Used")
    #ggplot(data=molten_space, aes(x=time, y=Bytes, group="time")) + geom_line() + scale_y_continuous("Space Used", labels=f2si)

1 个答案:

答案 0 :(得分:1)

这里有两个问题。

第一个问题是你使用生成列表的as.POSIXlt而不是生成向量的as.POSIXct。因此melt无法正常工作。试试这个:

df$time <- as.POSIXct(paste(df$Date, df$Time))

第二个问题是你对用于x轴的同一个变量进行分组,这对我来说没有多大意义。试试这个:

ggplot(data=molten_space, aes(x=time, y=value, color=variable)) + 
    geom_point() + geom_line() + scale_y_continuous("Space Used")

enter image description here

旁注

as.POSIXlt的用法通常是从数据中提取不同的组件。

   R> unlist(as.POSIXlt(df$time[1]))
       sec    min   hour   mday    mon   year   wday   yday  isdst   zone gmtoff 
       "1"    "0"    "7"    "9"    "5"  "115"    "2"  "159"    "1" "CEST" "7200"