稍作调整,您可以使用change-geom-texts-default-a-legend-to-label-string-itself 所示的方法。这改变了键生成函数,因此允许ggplot2 计算位置来为您放置标签。
我们的想法是为 geom_bar 图例键保留原始 rectGrob,并使用额外的 textGrob 将标签放在顶部。
library(ggplot2)
library(grid)
oldK <- GeomBar$draw_key # to save for later
# see other answer on how to tweak function based n manual colours
GeomBar$draw_key <- function (data, params, size,
var=unique(mtcars$vs),
cols=scales::hue_pal()(length(var))) {
# match labels to the fill colour
txt <- if(is.factor(var)) levels(var) else sort(var)
txt <- txt[match(data$fill, cols)]
# This is from the original GeomBar$draw_key -------------------
lwd <- min(data$size, min(size)/4)
rg <- rectGrob(width = unit(1, "npc") - unit(lwd, "mm"), height = unit(1,
"npc") - unit(lwd, "mm"), gp = gpar(col = data$colour,
fill = alpha(data$fill, data$alpha), lty = data$linetype,
lwd = lwd * .pt, linejoin = "mitre"))
# ---------------------------------------------------------------
# Add text label: lifted from other answer
# hard-coded text size multiplier -- got to be a better way!
tg <- textGrob(txt, 0.5, 0.5,
just="center",
gp = gpar(col = "black",
fontfamily = data$family,
fontface = data$fontface,
fontsize = 10*data$size * .pt))
# ---------------------------------------------------------------
grobTree(rg, tg) # output new key
}
然后你可以绘制
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar() +
theme(
legend.position = "top",
legend.direction = "horizontal",
legend.text = element_blank())
# reset key function to original
GeomBar$draw_key <- oldK
这对于调整绘图大小应该相当可靠。