如何在 R 中使用 ggplot2 增加水平图例之间的间距?


通常,两个图例条目之间的间距不够大,而若名称很长,则难以读取图例名称。在这种情况下,我们需要增加图例条目/名称之间的间距,但仅在图例水平对齐时才需要;垂直图例可以按原样读取。为此,我们可以使用 ggplot2 包的 theme 函数中的 legend.text 参数。

示例

考虑以下数据帧 -

动态演示

> x<-c("Male","Female")
> y<-c(501,520)
> df<-data.frame(x,y)
> df

输出

    x     y
1 Male   501
2 Female 520

加载 ggplot2 包并创建水平条形图 -

示例

> library(ggplot2)
> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+coord_flip()+theme(legend.position="bottom")+guides(fill=guide_legend(title=NULL))

输出

创建图例条目之间的间距较大的绘图 -

示例

> ggplot(df,aes(x,y,fill=x))+geom_bar(stat="identity")+coord_flip()+theme(legend.position="bottom",legend.text=element_text(margin=margin(r=1,unit="inch")))+guides(fill=guide_legend(title=NULL))

输出

更新于: 02-1 月-2021

1K+ 浏览量

开启您的 职业生涯

完成课程以取得认证

立即开始
广告
© . All rights reserved.