[英]Position a ggplot Legend label directly over its fill colour
对于ggplot图,我希望将图例的值(此处为0和1)定位在它们所代表的颜色上,而不是它们的侧面。 我的意思是不是在彩色正方形的左边,右边,上面或下面,而是在正方形内。 这将导致红色正方形内的数字0和蓝色正方形内的数字1。 如何才能做到这一点?
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar() +
theme(legend.position = "top",
legend.direction = "horizontal") +
guides(color = guide_legend(title.position = "left", label.position = "top"))
由于你正在使用fill
你需要在guides
使用填充,然后使用label.vjust
和title.vjust
来title.vjust
所有内容。
library(tidyverse)
ggplot(mtcars, aes(factor(cyl), fill = factor(vs))) +
geom_bar() +
theme(legend.position = "top",
legend.direction = "horizontal") +
guides(fill = guide_legend(label.vjust = -7, label.position = "top", title.vjust = 0.2))
由reprex包创建于2018-11-23(v0.2.1)
通过微调,您可以使用change-geom-texts-default-a-legend-to-label-string-their中显示的方法。 这会更改键生成功能,因此允许ggplot2
计算为您放置标签的位置。
我的想法是保留原始rectGrob
为geom_bar
图例键,并使用额外的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
这应该相当稳健,以调整你的情节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.