r - ggplot:使用分面图上方的单独数据添加注释
问题描述
我正在尝试在多面图表顶部添加一组带有文本的标记,以指示 x 值中的某些兴趣点。重要的是它们出现在从左到右的正确位置(根据主要比例),包括当整体 ggplot 改变大小时。
像这样的东西...
但是,我正在努力:
- 将其放置在正确的垂直位置(在刻面上方)。在下面的reprex(原始版本的简化版本)中,我尝试使用因子值(Merc450 SLC),但这会导致问题,例如将其添加到每个方面,包括当它不属于该方面并且不属于该方面时实际上足够高。我还尝试使用 as.integer 将因子转换为数字,但这会导致每个方面都包含所有因子值,而它们显然不应该
- 适用于整个图表,而不是每个方面
请注意,在完整解决方案中,标记 x 值与主要数据无关。
我尝试使用cowplot单独绘制并覆盖它,但这似乎:影响主图的整体比例,右侧的刻面标题被裁剪在将标记放置在沿x的确切位置时不可靠规模
欢迎任何指点。
library(tidyverse)
mtcars2 <- rownames_to_column(mtcars, var = "car") %>%
mutate(make = stringr::word(car, 1)) %>%
filter(make >= "m" & make < "n")
markers <- data.frame(x = c(max(mtcars2$mpg), rep(runif(nrow(mtcars2), 1, max(mtcars2$mpg))), max(mtcars2$mpg))) %>%
mutate(name = paste0("marker @ ", round(x)))
ggplot(mtcars2, aes()) +
# Main Plot
geom_tile(aes(x = mpg, y = car, fill = cyl), color = "white") +
# Add Markers
geom_point(data = markers, aes(x = x, y = "Merc450 SLC"), color = "red") +
# Marker Labels
geom_text(data = markers, aes(x = x, "Merc450 SLC",label = name), angle = 45, size = 2.5, hjust=0, nudge_x = -0.02, nudge_y = 0.15) +
facet_grid(make ~ ., scales = "free", space = "free") +
theme_minimal() +
theme(
# Facets
strip.background = element_rect(fill="Gray90", color = "white"),
panel.background = element_rect(fill="Gray95", color = "white"),
panel.spacing.y = unit(.7, "lines"),
plot.margin = margin(50, 20, 20, 20)
)
解决方案
也许绘制两个单独的图并将它们组合在一起patchwork
:
library(patchwork)
p1 <- ggplot(markers, aes(x = x, y = 0)) +
geom_point(color = 'red') +
geom_text(aes(label = name),
angle = 45, size = 2.5, hjust=0, nudge_x = -0.02, nudge_y = 0.02) +
scale_y_continuous(limits = c(-0.01, 0.15), expand = c(0, 0)) +
theme_minimal() +
theme(axis.text = element_blank(),
axis.title = element_blank(),
panel.grid = element_blank())
p2 <- ggplot(mtcars2, aes(x = mpg, y = car, fill = cyl)) +
geom_tile(color = "white") +
facet_grid(make ~ ., scales = "free", space = "free") +
theme_minimal() +
theme(
strip.background = element_rect(fill="Gray90", color = "white"),
panel.background = element_rect(fill="Gray95", color = "white"),
panel.spacing.y = unit(.7, "lines")
)
p1/p2 + plot_layout(heights = c(1, 9))
推荐阅读
- r - 如何在interaction.plot中排除时间戳?
- apache-kafka - Kafka-topics.sh 身份验证
- spring-boot - KeyCloak 15.0.2 & Spring boot:在获得“禁止”错误访问后,即使授权用户,API 也会持续发送相同的错误 403
- python - 当达到 2000000 个令牌时,有没有办法停止在 gensim.WikiCorpus 中创建词汇?
- python - 如何在 Python 的另一个线程中从异常中删除打印输出
- java - 循环遍历地图内的 3 个列表
- javascript - 具有不同 ID 的多个按钮到一个变量
- reactjs - 如何在 React 中使用来自 GET 请求的数据填充用户变量
- python - 自定义异常 python + Sentry stacktrace
- php - 在插件设置页面启用插件功能