问题在于绘图面板在绘制之前没有定义尺寸("NULL unit"),但你的图例指南却有。请参见
ggplot2中geom_point的npc坐标或
为ggsave(显示geom_dotplot计数的最终绘图的给定尺寸)找到面板尺寸。我认为以与面板完全相同的大小绘制图例指南将非常棘手。
然而,当处理复杂的图例格式时,您可以利用一个技巧:
创建一个虚假的图例。挑战在于调整填充比例尺以完美匹配您的图形范围(通常不会完全匹配您的数据值范围)。其余部分只是一些R语法。代码中有一些重要的注释。
library(ggplot2)
corrs <- structure(list(Var1 = structure(c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), levels = c("Var1", "Var2", "Var3"), class = "factor"), Var2 = structure(c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), levels = c("Var1", "Var2", "Var3"), class = "factor"), value = c(1, -0.11814395012334, -0.91732952510938, -0.969618394505233, 1, -0.00122085912153125, -0.191116513684392, -0.0373711776919663, 1)), class = "data.frame", row.names = c(NA, -9L))
range_fill <- range(corrs$value)
lim_fill <- c(floor(range_fill[1]), ceiling(range_fill[2]))
breaks_fill <- round(seq(lim_fill[1], lim_fill[2], len = 5), 2)
lim_y <- range(as.integer(corrs$Var2))
lim_x <- range(as.integer(corrs$Var1))
lim_vals <- lim_y + c(-.5, .5)
new_y <- scales::rescale(breaks_fill, lim_vals)
scl_x <- lim_x[2] + .7
scl_xend <- scl_x + .2
approx_fill <- approx(new_y, breaks_fill, n = 1000)
df_seg <- data.frame(y = approx_fill$x, color = approx_fill$y)
df_lab <- data.frame(y = new_y, x = scl_xend + .1, label = breaks_fill)
sep_len <- .05
df_sep <- data.frame(
y = new_y, yend = new_y,
x = rep(c(scl_x, scl_xend - sep_len), each = 5),
xend = rep(c(scl_x + sep_len, scl_xend), each = 5)
)
ggplot(corrs) +
geom_tile(aes(x = Var1, y = Var2, fill = value)) +
geom_segment(
data = df_seg,
aes(x = scl_x, xend = scl_xend, y = y, yend = y, color = color)
) +
geom_text(data = df_lab, aes(x, y, label = label), size = 9 * 5 / 14) +
geom_segment(
data = df_sep, aes(x = x, xend = xend, y = y, yend = yend),
color = "white"
) +
scale_fill_continuous(limits = lim_fill, breaks = breaks_fill) +
scale_color_continuous(limits = lim_fill, breaks = breaks_fill) +
coord_cartesian(xlim = lim_x, ylim = lim_y, clip = "off") +
theme(
legend.position = "none",
plot.margin = margin(r = 1, unit = "in")
)
![](https://i.imgur.com/j7qw15V.png)
创建于2022年12月29日,使用
reprex v2.0.2。