在R中绘制布尔值的时间顺序序列

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

我正在使用R。

假设我有一个按时间顺序排列的布尔值序列:W或L。

如何使用ggplot2获得与下面的图类似的内容?

enter image description here

r ggplot2
1个回答
0
投票

通过将geom_rect用于形状,将geom_text用于标签,将geom_bracket(来自ggpubr)用于轴上方或下方的标签,我有些工作。总体思路是沿轴绘制矩形或其他形状。您可以使用geom_label来创建盒子,但是很难设置宽度常数,尤其是在标签的长度不同的情况下。

# Data set for W/L record.  Time is arbitrary
set.seed(12345)
df <- data.frame(
  time=1:10,
  result=sample(c('W','L'),10,replace=TRUE)
)

# data set for labels
bracket.labels <- data.frame(
  x.from=c(1, 2, 5, 6),
  x.to=c(3, 5, 7, 10),
  lab=c('Weak', 'Had a problem', 'Good times', 'End of year')
)

# the plot
library(ggpubr)

ggplot(df, aes(x=time)) +
  geom_hline(yintercept=0) +
  geom_rect(aes(fill=result, xmin=time-0.4, xmax=time+0.4),
    ymin=-0.1, ymax=0.1, show.legend = FALSE) +
  geom_text(y=0, color='white',
    aes(label=result), fontface='bold') +
  ylim(-0.5,1.5) + theme_void() +
  scale_fill_manual(name=NULL, values=c('brown1', 'forestgreen')) +
  geom_bracket(data=bracket.labels, y.position=0.2,
    aes(xmin=x.from, xmax=x.to, label=lab),
    step.increase = 1, tip.length = 0.3)

enter image description here

您可能还可以使用其他解决方案,因为这是在响应中需要创造力的问题之一。其他方法可能涉及geom_tile的使用(我尝试过,但不喜欢)或通过自定义注释创建整个内容。

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