如何在 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))
输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP