2行ggplot2图例

问题描述

我找不到将ggplot2图例放在两行中的解决方案。

示例

library(ggplot2)
theme_set(theme_bw())
data("midwest",package = "ggplot2")

ggplot(midwest,aes(x=area,y=poptotal)) + 
  geom_point(aes(col=state,size=popdensity)) + 
  geom_smooth(method="loess",se=F) + 
  xlim(c(0,0.1)) + 
  ylim(c(0,500000)) + 
  labs(y="Population",x="Area",title="") +
  theme(legend.position = "top")

enter image description here

在上图中,我想在顶部(第一行)添加popdensity注释,在第二行中添加state注释。

解决方法

我认为您正在寻找theme(legend.box = "vertical")guide_legend(order = ...)

library(ggplot2)

data("midwest",package = "ggplot2")

ggplot(midwest,aes(x=area,y=poptotal)) + 
  geom_point(aes(col=state,size=popdensity)) + 
  geom_smooth(method="loess",se=F) + 
  xlim(c(0,0.1)) + 
  ylim(c(0,500000)) + 
  labs(y="Population",x="Area",title="") +
  theme_bw() +
  theme(legend.position = "top",legend.box = "vertical") +
  guides(size = guide_legend(order = 1),colour = guide_legend(order = 2))

enter image description here