之前和之后的时间范围图

问题描述 投票:0回答:1

可能的目标是生成这样的时间范围图。

这是玩具数据集

Group1  N       Year
A      10(10)   1999-2001
B      83(56)   2001-2004
C      100(94)  2006-2007
D      53(51)   2009-2011
E      20(19)   2012-2012
F      142(141) 2015-2016
G      34(32)   2015-2017
H      45(45)   2014-2018
I      21(19)   2016-2017
J      82(53)   2017-2019
K      12(12)   2021-2021

目标是以蓝色显示 2016 年以下的时间,以红色显示 2016 年以上的时间,以 2016 年之前的蓝色阴影显示 2016 年前后重叠的时间(G、H 组),以 2016 年之后的红色阴影显示。还有顶部的标签基于 N 列中的值的每个图。

我用 geom_errobar 尝试了一些东西,但事情失去了控制。非常感谢任何有关如何实现这一目标的帮助。谢谢。

r ggplot2 time range
1个回答
0
投票

这是使用

ggalt
包进行哑铃图的一个很好的用例:

library(ggplot2)
#install.packages("ggalt")
library(ggalt)  # For geom_dumbbell
library(dplyr)
library(tidyr)

data %>%
  separate(Year, into = c("StartYear", "EndYear"), convert = TRUE) %>% 
  mutate(Color = ifelse(StartYear < 2016 & EndYear > 2016, "overlap", 
                        ifelse(EndYear <= 2016, "before", "after"))) %>% 
  ggplot(aes(x = StartYear, xend = EndYear, y = Group1, yend = Group1, colour = Color)) +
  geom_dumbbell(size = 3) +
  geom_point(aes(x = StartYear, y = Group1), size = 3, show.legend = TRUE)+
  geom_text(aes(x = (StartYear + EndYear) / 2, label = N, vjust = -1)) +
  scale_colour_manual(values = c(before = "blue", after = "red", overlap = "purple")) +
  labs(title = "Time Range Dumbbell Plot", x = "Year", y = "Group", colour = "Period") +
  theme_minimal() +
  theme(legend.position = "bottom")

© www.soinside.com 2019 - 2024. All rights reserved.