簡體   English   中英

ggplot2 geom_linerange 刪除行之間的空白

[英]ggplot2 geom_linerange remove whitespace between rows

我正在嘗試創建類似於顯示中斷數據的條形圖記錄器的 plot。 中斷嚴重性是主要和次要的。 Plot 在兩行之間以及之前和之后有大量的垂直空白,我想刪除它以創建一個緊湊的兩行圖表。

dataframe 是:

> head(dfsub)
                StartDateTime                 EndDateTime Outage.DUR Outage.Severity
1 2021-07-01T00:23:33.0000000 2021-07-01T00:25:26.0000000  1.8833333           Minor
2 2021-07-01T00:25:26.0000000 2021-07-01T00:31:33.0000000  6.1166667           Major
3 2021-07-01T00:31:33.0000000 2021-07-01T00:40:34.0000000  9.0166667           Major
4 2021-07-01T00:40:34.0000000 2021-07-01T00:42:57.0000000  2.3833333           Minor
5 2021-07-01T00:42:57.0000000 2021-07-01T00:43:49.0000000  0.8666667           Minor
6 2021-07-01T00:43:49.0000000 2021-07-01T00:45:35.0000000  1.7666667           Minor

R 代碼我正在運行

ggplot(dfsub) +
  geom_linerange(aes(y = Outage.Severity, 
                     xmin = StartDateTime,
                     xmax = EndDateTime,
                     colour = as.factor(Outage.Severity)
                     ),
                 show.legend = FALSE,
                 size = 50) +
  scale_color_manual(values = c("red", "yellow")) +
  theme(legend.position = "none") +
  theme_test()

生成此 plotlinerange 情節 - 大量的空白

兩個建議。

  1. 您沒有問過這個問題,但是您的 x 軸已損壞,在分類意義上使用時間(這是一個連續的東西)。 請注意, R 和ggplot2將當前列視為字符串而不是時間戳 這很容易解決:

     dfsub[c("StartDateTime", "EndDateTime")] <- lapply(dfsub[c("StartDateTime", "EndDateTime")], as.POSIXct, format="%Y-%m-%dT%H:%M:%OS", tz="UTC")
  2. 我認為您不會使用geom_linerange對紅色和黃色之間的空白空間進行精細控制,我建議geom_rect作為選項。 這樣,刪除size= ,我們需要控制ymin=ymax= 這得益於將Outage.Severity設置為一個因素; 雖然不是完全必要,但這項工作通常會返回“如何更改 y 軸類別的順序?” ,對此唯一(理智)的反應是將它們轉換為因子並控制它們的levels= 我們還需要添加fill= ,而geom_linerange不需要。

     dfsub$Outage.Severity <- factor(dfsub$Outage.Severity) # add 'levels=' if you want to control the order

    從這里開始,知道分類數據是在整數上繪制的,我們將通過擴展它們的矩形 +/- 0.48 來填補它們之間的空白(任意,但應該可能接近但不超過/超過 0.5)。

     ggplot(dfsub) + geom_rect(aes(ymin = as.numeric(Outage.Severity)-0.48, ymax = as.numeric(Outage.Severity)+0.48, xmin = StartDateTime, xmax = EndDateTime, colour = Outage.Severity, fill = Outage.Severity), show.legend = FALSE) + scale_y_continuous(breaks = unique(as.numeric(dfsub$Outage.Severity)), labels = unique(dfsub$Outage.Severity)) + scale_color_manual(values = c("Major"="red", "Minor"="yellow")) + scale_fill_manual(values = c("Major"="red", "Minor"="yellow")) + theme(legend.position = "none") + theme_test()

在此處輸入圖像描述

暫無
暫無

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

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