我正在使用最新的 ggplot2,目前正在使用p + theme(legend.position='right'). 函数主题有很好的文档记录和组合bottom,right似乎不可能。但是,也许有另一种方法可以实现这一目标?
您可以使用 2 元素数字向量作为位置,例如:
p+theme(legend.position=c(0.85,0)
Run Code Online (Sandbox Code Playgroud)
问题是,它会重叠绘图区域。
如果你想强制它在一条水平线上,你可以添加:
p+guides(fill = guide_legend(nrow = 1))
Run Code Online (Sandbox Code Playgroud)
编辑
我用 plot.margin 来扩大底部的区域,你可以玩一下参数:
p+
guides(fill = guide_legend(nrow = 1))+
theme(plot.margin=unit(c(1,1,4,0.5),"cm"))+
theme(legend.position=c(0.85,-0.7))
Run Code Online (Sandbox Code Playgroud)
或者
p+
theme(plot.margin=unit(c(1,1,4,0.5),"cm")) +
theme(legend.position=c(0.85,-0.7))
Run Code Online (Sandbox Code Playgroud)
笔记
使用Rstudio,当我以特定的宽度*高度导出图像时,我没有得到图例,但是如果我在导出之前拖动并调整视图,如下所示,它可以工作。