ggplot legend.box.background 产生奇怪的遗迹

Gmi*_*ael 4 r ggplot2

这比我的上一个问题更难解释,因为这个问题不能完全重现。

我正在为几个地图生成图例,并在两个图例周围绘制一个框,因为一个图例只有 1 个项目(线要素),而其他图例是离散填充(多边形要素)。使用 geom_sf 绘制两者。

我最终得到了一个奇怪的人工制品,看起来部分线条被绘制了两次,只是位置略有偏移。

注意右下角!!!

我设法对 iris 数据集产生类似的错误,其中 legend.box.background 仅部分绘制。

data(iris)

ggplot(iris)+theme_classic()+
  geom_point(aes(x=Petal.Length, y=Sepal.Length, color=Species, size=Sepal.Width))+
  scale_color_manual(name=NULL, values=c("red","green","blue") ,labels=c("supersupersupersuperlong", "test2", "test3"))+
  theme(legend.position=c(0.1,0.75),legend.box.background=element_rect(fill="white", color="black"), legend.spacing.y=unit(0,"cm"))



Run Code Online (Sandbox Code Playgroud)

更新

我注意到在我原来的例子中它与文本长度有关,所以我尝试在一些标签后面添加一个空格,这稍微改变了两次绘制线的“排列”。但我找不到一种可以让它完全消失的空白排列方式。任何人都知道如何手动更改 legend.box.background 的大小。如果没有,我会画一个几何矩形并结束。

All*_*ron 5

我认为这里的问题是(它是图例的每个组件legend.background后面的白色矩形)部分绘制在围绕 的线上,这是围绕整个图例的矩形。您可以简单地删除legend.boxlegend.background

例如,你的情节是这样的:

ggplot(iris) + 
  theme_classic() +
  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
                 size = Sepal.Width)) +
  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
                     labels = c("supersupersupersuperlong", "test2", "test3")) +
  theme(legend.position = c(0.1, 0.75),
        legend.box.background = element_rect(fill = "white", color = "black"), 
        legend.spacing.y = unit(0, "cm"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

对此:

ggplot(iris) + 
  theme_classic() +
  geom_point(aes(x = Petal.Length, y = Sepal.Length, color = Species, 
                 size = Sepal.Width)) +
  scale_color_manual(name = NULL, values = c("red", "green", "blue"),
                     labels = c("supersupersupersuperlong", "test2", "test3")) +
  theme(legend.position = c(0.1, 0.75),
        legend.background = element_blank(),
        legend.box.background = element_rect(fill = "white", color = "black"), 
        legend.spacing.y = unit(0, "cm"))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述