使用时,如何调整图例颜色栏高度以匹配图的高度facet_wrap()
?此相关 SO 问题为单个图提供了一个很好的解决方案,但当存在多个图时,颜色栏会延伸到构面换行标题和轴文本的一半。我希望颜色栏仅从构面换行标题的底部延伸到轴文本的顶部。
制作基图
(注意小彩条的高度)
library(tidyverse)
library(ggcorrplot)
library(reshape2)
iris %>%
group_by(Species) %>%
summarise(correlation = list(cor(across(where(is.numeric))))) %>%
ungroup() %>%
mutate(correlation_df = map(correlation, ~ melt(.x, varnames = c("Var1", "Var2")))) %>%
select(Species, correlation_df) %>%
unnest(correlation_df) %>%
ggplot(aes(x = Var1, y = Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(limit = c(-1, 1)) +
labs(x = NULL,
y = NULL,
fill = NULL) +
theme_bw() +
facet_wrap(~Species)
使用类似问题的答案
(请注意颜色条延伸到标题和轴文本区域)
make_fullsize <- function() structure("", class = "fullsizebar")
ggplot_add.fullsizebar <- function(obj, g, name = "fullsizebar") {
h <- ggplotGrob(g)$heights
panel <- which(grid::unitType(h) == "null")
panel_height <- unit(1, "npc") - sum(h[-panel])
g +
guides(fill = guide_colorbar(barheight = panel_height,
title.position = "right")) +
theme(legend.title = element_text(angle = -90, hjust = 0.5))
}
iris %>%
group_by(Species) %>%
summarise(correlation = list(cor(across(where(is.numeric))))) %>%
ungroup() %>%
mutate(correlation_df = map(correlation, ~ melt(.x, varnames = c("Var1", "Var2")))) %>%
select(Species, correlation_df) %>%
unnest(correlation_df) %>%
ggplot(aes(x = Var1, y = Var2, fill = value)) +
geom_tile() +
scale_fill_gradient2(limit = c(-1, 1)) +
labs(x = NULL,
y = NULL,
fill = NULL) +
theme_bw() +
coord_cartesian(expand = FALSE) +
make_fullsize() +
facet_wrap(~Species)
创建于 2024-12-30,使用reprex v2.1.1
根据 Allan Cameron 的评论进行编辑:
通过在参数中将单位指定为 null
legend.key.height
,指南不仅可以垂直适应绘图,还可以在更改绘图的纵横比时拉伸。根据这篇tidyverse.org 文章,此功能仍处于实验阶段。(根据 Allan Cameron 的评论进行编辑)然后您可以
legend.margin = margin(0, 0, 0, 0)
在主题中添加内容,以便图例与图的顶部和底部垂直对齐。输出: