簡體   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