繁体   English   中英

ggplot:在x轴上打印小时格式

[英]ggplot:print hourly format in x-axis

我有以下数据框

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

但是,当前结果是:

在此处输入图片说明

在此处输入图片说明

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

 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轴。 非常感谢。

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

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

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

我不能说60分钟以上的时间条目格式,但这是一个可能的解决方案。 根据数据的分钟格式,可能需要其他处理。

将分钟转换为适当的格式,第一个左键盘为0(使用弦乐器包):

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

或上面链接中的sprintf()是一个简单,优雅的解决方案,该解决方案可以做到这一点: df$Time <- sprintf("%04d", df$Time)可能会更好,具体取决于您的原始时间格式。

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

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

然后在ggplot中适当格式化时间。 使用现有图,只需添加:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM