【问题标题】:pick the latest data set when doing geom_hline in ggplot2在 ggplot2 中做 geom_hline 时选择最新的数据集
【发布时间】:2013-03-14 18:31:46
【问题描述】:

输入(x)

structure(list(Host = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L), .Label = "A", class = "factor"), TimeStamp = structure(c(1L, 
2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), .Label = c("1/11/2013", 
"1/12/2013", "1/13/2013", "1/14/2013", "1/15/2013"), class = "factor"), 
    Instance = structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 
    2L), .Label = c("/application", "/db"), class = "factor"), 
    Free_Space = c(5048L, 5049L, 6000L, 4800L, 5100L, 317659L, 
    340000L, 350000L, 356666L, 370000L), Used_Space = c(3017L, 
    56000L, 60000L, 55000L, 54000L, 271657L, 150000L, 175000L, 
    165000L, 189999L), Total_Space = c(8064L, 61049L, 66000L, 
    59800L, 59100L, 589316L, 490000L, 525000L, 521666L, 559999L
    )), .Names = c("Host", "TimeStamp", "Instance", "Free_Space", 
"Used_Space", "Total_Space"), class = "data.frame", row.names = c(NA, 
-10L))

我有这个数据框。在给定主机、时间戳和实例的情况下,我通过使用 data.table 包添加 Free_Space 和 Used_Space 来驱动列名 Total_Space。

x<-data.table(x)
x<-x[,Total_Space:=Free_Space+Used_Space, by=c("Host", "Instance", "TimeStamp")]

我喜欢使用 ggplot2 中的 ggplot facet_wrap 来绘制以 GB 为单位的已用空间,并通过 Total_Space 绘制一个 geom_line,以便用户可以看到有多少空间。

例如,我正在这样做:

ggplot(x, aes(TimeStamp, Used_Space/1024, group=Instance)) + geom_area(fill="blue") + geom_smooth(method="lm", colour="orange",se=T, size=1) + geom_hline(data=x, aes(yintercept = Total_Space/1024), col="red")+ facet_wrap(~Host+Instance, ncol=3, scales="free") 

我看到的问题是我为同一个实例和主机获得了多个 geom_hline,因为 Total_Space 正在改变。

我的问题是,如何在为每个实例和主机执行 geom_hline 时选择最新的时间戳?我需要在 geom_hline 中显示最新的 Total_Space。

我试过这种方法:

x

没用。它为所有实例选择相同的数字。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    我的解决方案是,首先,将您的专栏 TimeStamp 设为日期

    x$TimeStamp<-as.Date(x$TimeStamp,format="%m/%d/%Y")
    

    那么,由于你的数据对象是data.table,你可以根据HostInstance对数据进行子集化,并将TimeStamp设置为最大值。

    x[,.SD[TimeStamp==max(TimeStamp)],by="Host,Instance"]
       Host     Instance  TimeStamp Free_Space Used_Space Total_Space
    1:    A /application 2013-01-15       5100      54000       59100
    2:    A          /db 2013-01-15     370000     189999      559999
    

    现在您可以在geom_hline() 中使用此行。使用scale_x_date(),您现在将获得更多控制此比例的可能性。

    library(scales)
    ggplot(x, aes(TimeStamp, Used_Space/1024, group=Instance)) + 
      geom_area(fill="blue") + geom_smooth(method="lm", colour="orange",se=T, size=1) + 
      geom_hline(data=x[,.SD[TimeStamp==max(TimeStamp)],by="Host,Instance"], aes(yintercept = Total_Space/1024), col="red")+ 
      facet_wrap(~Host+Instance, ncol=3, scales="free") +
      scale_x_date(labels = date_format("%m/%d/%Y"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-22
      • 1970-01-01
      • 2016-09-09
      • 2012-10-26
      • 2014-05-18
      相关资源
      最近更新 更多