你可以使用以下语法在ggplot2中创建一个多行的图例:
ggplot(df, aes(x=x_var, y=y_var, color=group_var)) +
geom_point() +
guides(color=guide_legend(nrow=2, byrow=TRUE))
nrow参数的值指定了图例中要使用的行数。
下面的例子展示了如何在实践中使用这种语法。
例子:在ggplot2中创建具有多行的图例
假设我们在R中拥有以下数据框,其中包含了各种篮球运动员的信息:
#create data frame
df <- data.frame(team=c('Mavs', 'Heat', 'Nets', 'Lakers', 'Suns', 'Cavs'),
points=c(24, 20, 34, 39, 28, 29),
assists=c(5, 7, 6, 9, 12, 13))
#view data frame
df
team points assists
1 Mavs 24 5
2 Heat 20 7
3 Nets 34 6
4 Lakers 39 9
5 Suns 28 12
6 Cavs 29 13
如果我们在ggplot2中创建散点图,而不指定图例中使用的行数,ggplot2将默认在每行放置一个标签:
library(ggplot2)
#create default scatterplot
ggplot(df, aes(x=assists, y=points, color=team)) +
geom_point(size=3)

为了创建一个多行的图例,我们必须使用带有nrow参数的**guide()**函数:
library(ggplot2)
#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
geom_point(size=3) +
guides(color=guide_legend(nrow=2, byrow=TRUE))

注意,图例现在有两行。
如果我们想改变图例的位置,我们可以使用带有legend.position参数的**theme()**函数:
library(ggplot2)
#create scatterplot with two rows in legend
ggplot(df, aes(x=assists, y=points, color=team)) +
geom_point(size=3) +
theme(legend.position='bottom') +
guides(color=guide_legend(nrow=2, byrow=TRUE))

图例现在位于绘图的底部,有两行。
其他资源
下面的教程解释了如何在ggplot2中执行其他常见操作: