r - 对齐cowplot中的共享图例
问题描述
我正在寻找使用 cowplot 包给两个 ggplots 一个共享的图例。但是,当有偶数个地块时,如何使共享图例居中。
这是一些示例代码:
library(ggplot2)
library(cowplot)
library(rlang)
# down-sampled diamonds data set
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
# function to create plots
plot_diamonds <- function(xaes) {
xaes <- enquo(xaes)
ggplot(dsamp, aes(!!xaes, price, color = clarity)) +
geom_point() +
theme_half_open(12) +
# we set the left and right margins to 0 to remove
# unnecessary spacing in the final plot arrangement.
theme(plot.margin = margin(6, 0, 6, 0))
}
# make two plots
p1 <- plot_diamonds(carat)
p2 <- plot_diamonds(depth) + ylab(NULL)
# arrange the three plots in a single row
prow <- plot_grid(
p1 + theme(legend.position="none"),
p2 + theme(legend.position="none"),
align = 'vh',
labels = c("A", "B"),
hjust = -1,
nrow = 1
)
prow
# extract a legend that is laid out horizontally
legend_b <- get_legend(
p1 +
guides(color = guide_legend(nrow = 1)) +
theme(legend.position = "bottom")
)
# add the legend underneath the row we made earlier. Give it 10%
# of the height of one plot (via rel_heights).
plot_grid(prow, legend_b, ncol = 1, rel_heights = c(1, .1))
生成此图像:
如您所见,cow_plot 将图例置于左图下方。有没有办法让这个共享的图例居中在两个图像之间?
解决方案
更改theme
如下;
legend_b <- get_legend( p1 +
guides(color = guide_legend(nrow = 1)) +
theme(legend.direction = "horizontal",
legend.justification="center",
legend.box.just = "bottom")
)
推荐阅读
- php - 将mysql数据添加到HTML表中
- c# - Get inner JSON content as string without deserializing
- google-cloud-platform - 无法将 350 GB 数据从一个存储桶复制到谷歌云中的另一个存储桶
- unity3d - 建造一堵提高速度统一的墙
- python - 如何避免在 Django 中使用 context_processors.py 时在登录页面上请求用户?
- wordpress - 来自 WP REST API 的类别的 Vuejs vfor 循环中的 SVG
- oracle - 一个多小时前在 Apex Oracle 中创建的不同颜色记录
- json - 按值排序json数组jq bash
- java - 根据孩子的领域对抽象对象列表进行排序
- python - 如何降低计算成本