当传奇标题很长时,我很难将传奇中心的标题相对于图例键对齐。 a year ago有一个问题适用于短标题,但它似乎不适用于长标题。
示例,首先使用简短的图例标题:
library(ggplot2)
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Petal.Width)) + geom_point(size = 3) +
scale_color_distiller(palette = "YlGn", type = "seq", direction = -1,
name = "A") +
theme(legend.title.align = 0.5)
一切都如预期的那样,图例标题位于图例键的上方。
现在和一个长长的传奇标题相同:
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Petal.Width)) + geom_point(size = 3) +
scale_color_distiller(palette = "YlGn", type = "seq", direction = -1,
name = "Long legend heading\nShould be centered") +
theme(legend.title.align = 0.5)
我们可以看到文本中心与自身对齐,但与图例键无关。我已经尝试修改其他主题选项,例如legend.justification = "center"
,但似乎没有人从图例框中最左边的位置移动键。
几条评论:
我找到了解决方案。它需要一些挖掘到grob树,如果有多个传说它可能不起作用,但除非有更好的东西出现,否则这似乎是一个合理的解决方案。
library(ggplot2)
library(gtable)
library(grid)
p <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Petal.Width)) +
geom_point(size = 3) +
scale_color_distiller(palette = "YlGn", type = "seq", direction = -1,
name = "Long legend heading\nShould be centered") +
theme(legend.title.align = 0.5)
# extract legend
g <- ggplotGrob(p)
grobs <- g$grobs
legend_index <- which(sapply(grobs, function(x) x$name) == "guide-box")
legend <- grobs[[legend_index]]
# extract guides table
guides_index <- which(sapply(legend$grobs, function(x) x$name) == "layout")
guides <- legend$grobs[[guides_index]]
# add extra column for spacing
# guides$width[5] is the extra spacing from the end of the legend text
# to the end of the legend title. If we instead distribute it 50:50 on
# both sides, we get a centered legend
guides <- gtable_add_cols(guides, 0.5*guides$width[5], 1)
guides$widths[6] <- guides$widths[2]
title_index <- guides$layout$name == "title"
guides$layout$l[title_index] <- 2
# reconstruct legend and write back
legend$grobs[[guides_index]] <- guides
g$grobs[[legend_index]] <- legend
grid.newpage()
grid.draw(g)
你必须改变源代码。目前它在视口(gtable)中有computes the widths for the title grob and the bar+labels和left-justifies the bar+labels。这是硬编码的。