簡體   English   中英

時間序列ggplot中x軸上的時間戳

[英]Timestamp on x-axis in timeseries ggplot

我有過去幾個月的測量數據:

在此處輸入圖片說明

變數

 x <- df$DatoTid
 y <- df$Partikler
 color <- df$Opgave

我正在嘗試根據時間戳繪制數據,以便在x軸上顯示一天中的時間,而不是特定的POSIXct日期時間。 我希望x軸的標簽和刻度為fx“ 00:00”,“ 01:00”,...“ 24:00”。 這樣中午在x軸的中間。

到目前為止,我嘗試將datetime值轉換為字符。 看起來還不太好(如您所見,軸刻度線和標簽都消失了。可能其他情況也是錯誤的)。

有人能幫我嗎? 並且請讓我知道如何為您上傳數據。 我不知道如何添加巨大的.csv文件...

在此處輸入圖片說明

# Rounding up to nearest 10 min: 
head(df)
df$Tid2 <- format(strptime("1970-01-01", "%Y-%m-%d", tz="CET") + 
round(as.numeric(df$DatoTid)/300)*300 + 3600, "%Y-%m-%d %H:%M:%S")
head(df)
df$Tid2 <- as.character(df$Tid2)
str(df)

x <- df$Tid2
y <- df$Partikler
color <- df$Opgave

plot2 <- ggplot(data = df, aes(x = x, y = y, color = color)) +
  geom_point(shape=16, alpha=0.6, size=1.8) +
  scale_y_continuous(labels=function(x) format(x, big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_x_discrete(breaks=c("00:00:00", "06:00:00", "09:00:00", "12:00:00", "18:00:00", "21:00:00")) +
  scale_color_discrete(name = "Case") +
  xlab(" ") +
  ylab(expression(paste("Partikelkoncentration [pt/cc]"))) +
  myTheme + 
  theme(legend.text=element_text(size=8), legend.title=element_text(size=8))
plot2

我可以通過制作一個新的時間戳來解決這一問題,該時間戳使用一天的時間,但是要使用現有時間戳的小時/分鍾/秒。

首先,這是數據的Partikler版本,在這里使用Partikler的線性趨勢:

library(tidyverse); library(lubridate)
df <- data_frame(Tid2 = seq.POSIXt(from = ymd_h(2019010100), 
                                   to = ymd_h(2019011500), by = 60*60),
                 Partikler = seq(from = 0, to = 2.5E5, along.with = Tid2),
                 Opgave = as.factor(floor_date(Tid2, "3 days")))

# Here's a plot that's structurally similar to yours:
ggplot(df, aes(Tid2, Partikler, col = Opgave)) + 
  geom_point() +
  scale_color_discrete(name = "Case")

在此處輸入圖片說明

現在,如果我們將時間戳記更改為同一天,則可以像在ggplot中一樣正常地控制它們,但是將它們壓縮為一天的時間。 我們還可以更改x軸,以便不提及時間戳記的日期部分:

df2 <- df %>%
  mutate(Tid2_sameday = ymd_hms(paste(Sys.Date(), 
                                      hour(Tid2), minute(Tid2), second(Tid2))))


ggplot(df2, aes(Tid2_sameday, Partikler, col = Opgave)) + 
  geom_point() +
  scale_color_discrete(name = "Case")  +
  scale_x_datetime(date_labels = "%H:%M")

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM