我使用ggplot2
中的自定义图例创建了一个情节。我试图在图例中的所有项目周围绘制一个框,但是我只能在每个单独的项目周围绘制一个框。如何围绕所有项目只创建一个框?
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point(aes(shape = "Data")) +
stat_smooth(aes(linetype = "Regression"), method = "lm",
formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
scale_shape_manual(values = 1) +
labs(shape = "", linetype = "") +
theme_classic() +
theme(panel.border = element_rect(colour = "black", fill=NA),
aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
legend.background = element_rect(linetype = 2, size = 0.5, colour = 1))
答案 0 :(得分:12)
似乎legend.background
矩形与legend.box.background
矩形重叠。一个简单的解决方法是设置legend.background = element_blank()
。
但是,在我看来,传说中的间距很难看。即使没有标题设置,图例标题也会占用太多空间。修复此设置legend.title = element_blank()
。两个图例之间的间距也太大。通过将空格设置为零legend.spacing.y = unit(0, "mm")
library(ggplot2)
ggplot(mpg, aes(displ, cty)) +
geom_point(aes(shape = "Data")) +
stat_smooth(aes(linetype = "Regression"), method = "lm",
formula = y ~ x, se = FALSE, colour = 1, size = 0.5) +
scale_shape_manual(values = 1) +
labs(shape = "", linetype = "") +
theme_classic() +
theme(legend.title = element_blank(),
legend.spacing.y = unit(0, "mm"),
panel.border = element_rect(colour = "black", fill=NA),
aspect.ratio = 1, axis.text = element_text(colour = 1, size = 12),
legend.background = element_blank(),
legend.box.background = element_rect(colour = "black"))