繁体   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