在图例ggplot2周围绘制一个框 [英] Draw a box around a legend ggplot2

查看:122
本文介绍了在图例ggplot2周围绘制一个框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用ggplot2中的自定义图例创建了一个图.我试图在图例中的所有项目周围画一个盒子,但是我只能在每个单独的项目周围画一个盒子.如何在所有项目周围仅创建一个框?

I created a plot with a custom legend in ggplot2. I tried to draw a box around all the items in the legend, however I could only draw a box around each individual item. How can I create only one box around all the items?

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))

推荐答案

似乎legend.background矩形与legend.box.background矩形重叠.一个简单的解决方法是设置legend.background = element_blank().

It seems that the legend.background rectangle overlaps the legend.box.background rectangle. An easy fix is to set legend.background = element_blank().

但是,在我看来,图例中的间距很难看.图例标题即使没有设置标题也会占用太多空间.修复此问题,将其设置为legend.title = element_blank().同样,两个图例之间的间距太大.通过将空格设置为零来解决此问题legend.spacing.y = unit(0, "mm")

But then, in my opinion, the spacing in the legend is ugly. The legend titles take up too much space even with no title set. Fix this be setting legend.title = element_blank(). Also the spacing between the two legends is too large. Fix this by setting the space to zero 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"))

这篇关于在图例ggplot2周围绘制一个框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆