多个几何图形双边框的图例

时间:2019-02-01 18:20:04

标签: r ggplot2 legend-properties

我正在将此用于地图,我希望栅格图层和点数据显示在图例中,该图例位于地图空白内的实际图上。但是,执行此操作时,图例的某些侧面会弹出奇怪的双边框线,这可能是因为两个图例的大小不同。我不确定是否有办法固定两个图例大小以匹配,或者找到图例大小并在图例周围添加我自己的矩形。这是一个产生相同问题的简化版本。我已经显示了代码,包括边框和没有边框的代码,您可以看到图例大小略有不同。

library(RColorBrewer)
library(ggplot2)
library(raster)

r = raster()
r[] = 1:ncell(r)

df = as.data.frame(r, xy=TRUE)

x <- sample(-75:75, 100)
y <- sample(-75:75, 100)
xy <- data.frame(cbind(x,y))

plot <- ggplot(df) +
  geom_raster(aes(x, y, fill=layer)) +
  geom_point(data=xy, aes(x=x, y=y, colour="Purple Points"))+
  scale_colour_manual(values = c("Purple Points"="purple"))+
  scale_fill_distiller(palette='RdYlGn')+
  theme(panel.background = element_rect(fill="white"),
        panel.border = element_rect(color="black", fill=NA, size=1.2),
        axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank(),
        legend.box.background = element_rect(color='black', fill="white", size=1.5),
        legend.position = c(0.1,0.1),
        legend.justification = c(0,0),
        legend.key.height = unit(.25,"cm"),
        legend.key.width = unit(.6, "cm"),
        legend.title=element_text(size=8, vjust=2.5),
        legend.key = element_rect(colour = NA, fill = NA),
        legend.text = element_text(size=6),
        legend.spacing.y = unit(0, "cm"))
plot

产生:

Plot with strange border

plot <- ggplot(df) +
  geom_raster(aes(x, y, fill=layer)) +
  geom_point(data=xy, aes(x=x, y=y, colour="Purple Points"))+
  scale_colour_manual(values = c("Purple Points"="purple"))+
  scale_fill_distiller(palette='RdYlGn')+
  theme(panel.background = element_rect(fill="white"),
        panel.border = element_rect(color="black", fill=NA, size=1.2),
        axis.text.x = element_blank(),
        axis.title.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.text.y = element_blank(),
        axis.title.y = element_blank(),
        axis.ticks.y = element_blank(),
        panel.grid = element_blank(),
        legend.position = c(0.1,0.1),
        legend.justification = c(0,0),
        legend.key.height = unit(.25,"cm"),
        legend.key.width = unit(.6, "cm"),
        legend.title=element_text(size=8, vjust=2.5),
        legend.key = element_rect(colour = NA, fill = NA),
        legend.text = element_text(size=6),
        legend.spacing.y = unit(0, "cm"))

此代码不包含对主题的legend.background()调用,并生成此绘图,您可以在其中看到两个图例的不同大小。

No border, but different legend sizes

0 个答案:

没有答案