使用长标签名称ggplot设置标准图例键大小
我正在构建一个 ggplot 可视化,其中一些填充美学具有很长的变量名称,而其他变量名称很短。添加长名称会更改与长文本对应的图例键的大小 - 将其加长以匹配文本。我想知道是否有办法标准化所有变量的图例键高度,并更改图例项之间的空格。
我尝试修改theme(legend.key.height()),theme(legend.key.width())但这并没有解决问题。
这是示例代码:
#load neccesary package
library('ggplot2')
#create the dataframe
df <- data.frame(year = as.integer(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)),
class = c('A', 'B', 'C', 'D', 'E'),
value = c(50, 50))
#Create plot
g <- ggplot(df, aes(x = year, y = value, fill = class)) +
geom_col(position = 'stack') +
scale_fill_discrete(labels = c('This is annextremelynlong labelnname', 'short label1', 'Anothernlongnlabelnname', 'short label3', 'short label4'))
情节:
我想要的是所有变量都具有相同的键大小,键之间的空白会发生变化以适应长文本。所以看起来像这样:
试 g + theme(legend.key.height = unit(3, 'mm'), legend.key.width = unit(3, 'mm'))
不能解决问题。
有什么想法吗?
回答
您可以通过定义自己的图例类来做到这一点。这当然比主题中的简单选项更冗长,了解一些 gtable/grid 会很方便,但它可以完成工作。
library(ggplot2)
library(grid)
#create the dataframe
df <- data.frame(year = as.integer(c(1, 1, 1, 1, 1, 2, 2, 2, 2, 2)),
class = c('A', 'B', 'C', 'D', 'E'),
value = c(50, 50))
labs <- c('This is annextremelynlong labelnname', 'short label1',
'Anothernlongnlabelnname', 'short label3', 'short label4')
guide_squarekey <- function(...) {
# Constructor just prepends a different class
x <- guide_legend(...)
class(x) <- c("squarekey", class(x))
x
}
guide_gengrob.squarekey <- function(guide, theme) {
# Make default legend
legend <- NextMethod()
# Find the key grobs
is_key <- startsWith(legend$layout$name, "key-")
is_key <- is_key & !endsWith(legend$layout$name, "-bg")
# Extract the width of the key column
key_col <- unique(legend$layout$l[is_key])
keywidth <- convertUnit(legend$widths[2], "mm", valueOnly = TRUE)
# Set the height of every key to the key width
legend$grobs[is_key] <- lapply(legend$grobs[is_key], function(key) {
key$height <- unit(keywidth - 0.5, "mm") # I think 0.5mm is default offset
key
})
legend
}
ggplot(df, aes(x = year, y = value, fill = class)) +
geom_col(position = 'stack') +
scale_fill_discrete(labels = labs,
guide = "squarekey")
由reprex 包(v0.3.0)于 2021 年 1 月 20 日创建
编辑:如果您也想编辑关键背景:
guide_gengrob.squarekey <- function(guide, theme) {
legend <- NextMethod()
is_key <- startsWith(legend$layout$name, "key-")
is_key_bg <- is_key & endsWith(legend$layout$name, "-bg")
is_key <- is_key & !endsWith(legend$layout$name, "-bg")
key_col <- unique(legend$layout$l[is_key])
keywidth <- convertUnit(legend$widths[2], "mm", valueOnly = TRUE)
legend$grobs[is_key] <- lapply(legend$grobs[is_key], function(key) {
key$height <- unit(keywidth - 0.5, "mm")
key
})
legend$grobs[is_key_bg] <- lapply(legend$grobs[is_key_bg], function(bg) {
bg$height <- unit(keywidth, "mm")
bg
})
legend
}