对于 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"))
Run Code Online (Sandbox Code Playgroud)
由于您正在使用,因此fill您需要使用填充,guides然后使用label.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))
Run Code Online (Sandbox Code Playgroud)

由reprex 包(v0.2.1)于 2018 年 11 月 23 日创建