【问题标题】:ggplot:print hourly format in x-axisggplot:在 x 轴上打印每小时格式
【发布时间】:2017-05-19 08:45:34
【问题描述】:

我有以下数据框

df

Time Load1 Load2

0 375.5 375.5

10 374.6 374.6

20 350.1 350.1

30 334.5 334.5

40 304.9 347.7

50 285.4 331.6

.... .... .. ...

我无法将时间列的格式从 10,20 更改为:00:10, 00:20...

我想通过这个命令使用 ggplot 绘制这个数据框:

    P<- ggplot(df,aes(Time))+

    geom_line(aes (y=0))+

   geom_vline(xintercept = 0,)+  

    geom_line(aes(y=Load2,linetype = "twodash"))+ 

    geom_line(aes(y=Load1, linetype = "solid"))+

    theme(legend.position='none')+ # to remove the legend.

    geom_vline(xintercept = 650, colour="purple",linetype ="longdash")+

    geom_vline(xintercept = 1500, colour="purple",linetype ="longdash")+

    geom_vline(xintercept = 2200, colour="purple",linetype ="longdash")+

    labs(title = "Daily load demands", x = "Time of day", y = "Power 
consumption_Kw/h")

    P

但是,目前的结果是:

enter image description here

我尝试了以下命令来更改时间格式:

 df<- data.frame(Time,Load1,Load2)

 df$Time <- as.POSIXct(df$Time, format="%H:%M:%S")
   P<- ggplot(df,aes(df$Time))+...

但是没有变化。请问,是否有任何建议以 05:00、10:00、15:00、20:00 格式而不是 500、1000、1500、2000 格式绘制 x 轴。非常感谢。

【问题讨论】:

  • 只是为了理解。如果在您的数据框中您有10 那将是10:00?因为我在您的数据框中没有看到 10,20 之类的东西... 编辑:哦,好的,我现在明白了。 10 只需要 10 分钟吧?
  • 重复:检查这个答案stackoverflow.com/questions/25272457/…
  • 感谢 fasttouch 的回答。首先抱歉不清楚的问题。是的,“00:10”格式的 10 只需要 10 分钟,但是“10:00”格式的 1000 需要是上午 10 点。我想在图中显示出来。谢谢。
  • 感谢@fasttouch 的重复:检查答案链接,我通过以下代码更改格式:temp2

标签: r plot ggplot2


【解决方案1】:

我想这可能是您的解决方案。如果只是可视化问题(而不是数据问题),为什么不简单地更改 ggplot 中的标签?您可以使用类似于(注意:我在这里给您的代码只是一个示例,不适用于您的案例)

scale_x_continuous( breaks = c(2012,2013,2014,2015,2016, 2017), 
      labels = c ("A","B","C","D","E","F"))

这会将 x 轴上的标签从年份更改为字母。

【讨论】:

    【解决方案2】:

    我无法确定超过 60 分钟的时间条目的格式,但这是一个可能的解决方案。根据数据的分钟格式,可能需要其他操作。

    将分钟转换为适当的格式,首先用 0 左填充(使用 stringr 包):

    df$Time <- stringr::str_pad(df$Time, 4, "left", pad = "0" )
    

    或上面链接中的sprintf() 是一种简单而优雅的解决方案,其作用相同:df$Time &lt;- sprintf("%04d", df$Time) 根据您的原始时间格式,一个可能会更好。

    然后将其转换为 POSIXct 格式时间:

    df$Time <- strptime(df$Time, format = "%H%M")
    

    然后在 ggplot 中适当地格式化时间。使用您现有的情节,只需添加:

    P + scale_x_datetime(labels = date_format("%H:%M"))
    

    【讨论】:

    • 非常感谢@Matt L.,通过添加您的代码,您的答案可以解决大部分问题。但是,我需要三件事来管理新人物。这些是今天的日期(月和日数),带有 X 轴标签。第二,次日00:00。第三,竖线消失了,我需要将它们返回,如下面的链接为新的图形图像:liveplymouthac-my.sharepoint.com/personal/…多谢
    猜你喜欢
    • 2023-03-30
    • 2018-02-03
    • 1970-01-01
    • 2016-10-12
    • 1970-01-01
    • 2018-03-27
    • 1970-01-01
    • 2020-06-25
    • 2021-09-10
    相关资源
    最近更新 更多