考虑一个最小的例子:
signals <- tibble(
time = 1:20,
long = c(rep(0,10),rep(1,10)),
medium = c(rep(0,5),rep(1,5),rep(0,5),rep(1,5)),
short = c(rep(0,2),rep(1,2),rep(0,2),rep(1,2),rep(0,2),rep(1,2),rep(0,2),rep(1,2),rep(0,2),rep(1,2)),
random = c(sample(2,20,TRUE)-1)
)
signals %<>%
pivot_longer(!time,names_to = "signals")
Run Code Online (Sandbox Code Playgroud)
我想使用 ggplot 来显示各种 1 或 0 的信号。我研究了点图和条形图,但不知何故我一直把它们变成直方图,这是我不想要的。我将如何创建一个通常看起来像这样的图,但不是直方图:
您可以将数据旋转为长格式,然后只需在 x 轴上绘制时间,name在 y 轴上绘制旋转数据框的列。这fill将是value列:
ggplot(tidyr::pivot_longer(signals, -time),
aes(time, name, fill = factor(value))) +
geom_point(size = 8, shape = 21) +
scale_y_discrete('Signals') +
scale_fill_manual('Value', values = c('white', 'black')) +
theme_gray(base_size = 16)
Run Code Online (Sandbox Code Playgroud)
然而,创建二进制信号图的更典型方法是使用geom_step:
ggplot(tidyr::pivot_longer(signals, -time), aes(time, value)) +
geom_step(linewidth = 1) +
scale_y_continuous('Signals', expand = c(0.5, 0.5)) +
scale_x_continuous('Time (s)', limits = c(0, 20)) +
facet_grid(name~., switch = 'y') +
theme_minimal(base_size = 16) +
theme(panel.spacing.y = unit(0, 'mm'),
axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank(),
strip.background = element_blank(),
strip.text.y.left = element_text(size = 14, angle = 0, hjust = 1))
Run Code Online (Sandbox Code Playgroud)