在 ggplot2 之上叠加基本 R 图形

Overlay base R graphics on top of ggplot2

我在 ggplot 中有一个绘图,我希望覆盖我用基本 R 代码创建的地图图例。我不知道如何在 ggplot 上叠加基本 R 图形,非常感谢您的帮助。

目前我有一个 ggplot 图例,如下所示:

这个图例有几处我不喜欢,我想更改(这导致我认为使用基本 R 图形会更容易)。

特别是,我希望消除图例中方框之间的白色 space,我也希望在方框之间添加刻度线。我还希望将“5”放在分隔第一个和第二个框的第一个刻度线下方;分隔第二个和第三个框的刻度线下方的“10”;和分隔第三个和第四个框的刻度线下方的“20”。我还希望使图例中的框与我绘图中的 "bins" 之一大小相同(我使用 stat_bin2d 层)。

相关代码:

ggplot()+
stat_bin2d(restaurants.df,binwidth=c(1500,2500), alpha=0.6,aes(x=X,y=Y,fill=cut(..count.., c(0,5,10,20,Inf))))+
scale_fill_manual("No. of Restaurants",labels=c("<5","5-10","10-20",">20"),values=cols, guide = guide_legend(direction = "horizontal", title.position = "top",                                      ticks=TRUE,label.position="bottom")) + 
theme(legend.background = element_rect(colour = "black"),
    legend.key = element_rect(color='black'))

@baptiste 的评论让我有兴趣尝试创建一个将成为传奇的情节。这是我的尝试。我用 geom_tile 创造了一个将成为传奇的情节。 OP 没有提供示例数据,所以我使用内置的 mtcars 数据创建了一个图,只是为了在图例旁边放置一些东西。然后我使用 grid.arrange 创建最终的 plot-plus-legend 布局。

library(ggplot2)
library(grid)
library(gridExtra) 

## Create legend

# Fake data
dat = data.frame(x=1:4, y="Group", col=factor(1:4))

# Create a plot that will become the legend
legend = ggplot(dat, aes(x,y, fill=col)) + 
  geom_tile(show.legend=FALSE) +
  scale_x_continuous(breaks=c(1.5,2.5,3.5), labels=c(5,10,20)) +
  scale_fill_manual(values=c("yellow","orange","red","darkred")) +
  labs(y="", x="") +
  ggtitle("No. of Restaurants") +
  theme_bw() +
  theme(panel.border=element_blank(),
        axis.ticks.y=element_blank(),
        axis.text.y=element_blank())

## Create a plot to put next to the legend
p1 = ggplot(mtcars, aes(mpg, wt)) + 
  geom_point() +
  theme(plot.margin=unit(c(0,0,0,0)))

# Arrange plot and legend
grid.arrange(p1, arrangeGrob(rectGrob(gp=gpar(col=NA)), 
                             legend,
                             rectGrob(gp=gpar(col=NA)),
                             heights=c(0.42,0.16,0.42)), 
             widths=c(0.8,0.2))

定义您自己的自定义图例可能会更容易,

library(gridExtra)
library(grid)

stripGrob <- function(cols = c("yellow","orange","red","darkred"), 
                      labels= c(5,10,20), 
                      gp=gpar(fontsize=10,fontface="italic"), vp=NULL){
  n <- length(cols)
  rg <- rasterGrob(t(cols), y=1, vjust=1, interpolate = FALSE)
  sg <- segmentsGrob(x0=seq(1/n, 1-1/n, length.out=n-1),
                     x1=seq(1/n, 1-1/n, length.out=n-1),
                     y0=unit(1,"npc") - grobHeight(rg),
                     y1=unit(1,"npc") - grobHeight(rg) - unit(2,"mm"),
                     gp=gpar(lwd=2))
  tg <- textGrob(labels, x=seq(1/n, 1-1/n, length.out=n-1),
                 unit(1,"npc") - grobHeight(rg) - grobHeight(sg) - unit(1,"mm"), 
                 vjust=1)

  stripGrob <- gTree(children = gList(rg, tg, sg), gp=gp, vp=vp)
}

qplot(1,1) +
  annotation_custom(grob=stripGrob(), xmax=1.0)