【问题标题】:Show limited time range on x-axis with ggplot使用 ggplot 在 x 轴上显示有限的时间范围
【发布时间】:2016-06-11 08:25:45
【问题描述】:

我希望下图中的 x 轴从 06:00 开始,到 22:00 结束,每 4 小时休息一次。但是,我无法弄清楚以下内容。

a) 如何使 x 轴从 06:00 开始,在 06:00 之前没有任何空白。

b) 如何使 x 轴在 22:00 结束,22:00 之后没有任何空白。现在它甚至没有显示 22:00

c) 如何每 4 小时休息一次。

d) 如何为 y 轴分配标签(目前只是 X4,列名)。

我尝试了几件事,但都没有成功。一些示例数据:

range <- seq(as.POSIXct("2015/4/18 06:00"),as.POSIXct("2015/4/18 22:00"),"mins")

df <- data.frame(matrix(nrow=length(range),ncol=4))
df[,1] <- c(1:length(range))
df[,2] <- 2*c(1:length(range))
df[,3] <- 3*c(1:length(range))
df[,4] <- range

重塑:

library(reshape2)
df2 <- melt(df,id="X4")

图表:

library(ggplot2)
ggplot(data=df2,aes(x=X4,y=value,color=variable)) + geom_line()+
  scale_y_continuous(expand=c(0,0)) +
  coord_cartesian(xlim=c(as.POSIXct("2015/4/18 06:00:00"),as.POSIXct("2015/4/18 22:00:00")))

这使得图表看起来像这样:

有什么想法吗?

【问题讨论】:

    标签: r time ggplot2


    【解决方案1】:

    这里有一些可以帮助你的代码。这可以使用scale_x_datetime 轻松完成。

    ## desired start and end points
    st <- as.POSIXct("2015/4/18 06:00:00")
    nd <- as.POSIXct("2015/4/18 22:00:00")
    
    ## display data for given time range
    ggplot(data = df2, aes(x = X4, y = value, color = variable)) + 
      geom_line() +
      scale_y_continuous("Some name", expand = c(0, 0)) +
      scale_x_datetime("Some name", expand = c(0, 0), limits = c(st, nd), 
                       breaks = seq(st, nd, "4 hours"), 
                       labels = strftime(seq(st, nd, "4 hours"), "%H:%S"))
    

    【讨论】:

    • 完美运行!谢谢。
    猜你喜欢
    • 2018-07-10
    • 1970-01-01
    • 2018-05-20
    • 1970-01-01
    • 2013-06-10
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    相关资源
    最近更新 更多