ggplot2 - 将带有描述性注释的框添加到 ggplot2 中的 y 轴
问题描述
我正在尝试向我的 Y 轴添加另一个标签或描述。我附上了一张图片以供我尝试完成的工作的参考。我找不到任何描述如何向轴添加其他元素的内容。它是“我试图将其合并到我的 ggplot 中的 Y 轴旁边的“好”和“坏”框。谢谢!
解决方案
实现此目的的一种方法是使用patchwork
. 您可以将 y 轴的注释设置为第二个 ggplot,并使用patchwork
. 尝试这个:
library(ggplot2)
library(patchwork)
library(dplyr)
p1 <- tibble(x = 1:10, y = 1:10) %>%
ggplot(aes(x, y)) +
geom_point() +
scale_y_reverse(breaks = seq(1, 10)) +
labs(y = NULL)
p2 <- tibble(ymin = c(0, 4), ymax = c(4, 10), fill = c("bad", "good")) %>%
ggplot() +
geom_rect(aes(xmin = 0, xmax = 1, ymin = ymin, ymax = ymax, fill = fill)) +
geom_text(aes(x = .5, y = (ymin + ymax) / 2, label = fill), angle = 90) +
scale_y_reverse(breaks = seq(1, 10), expand = expansion(mult = c(0, 0))) +
scale_x_continuous(breaks = c(0), expand = expansion(mult = c(0, 0))) +
guides(fill = FALSE) +
theme_void()
p2 + p1 + plot_layout(widths = c(1, 9))
由reprex 包(v0.3.0)于 2020 年 5 月 28 日创建