如何在不绘制符号的情况下在R中绘制图例并仍然使其对齐良好? [英] How can I plot a legend in R without plotting symbols and still get it to align nicely?

查看:77
本文介绍了如何在不绘制符号的情况下在R中绘制图例并仍然使其对齐良好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建没有图例符号且文本本身适合边框的图例吗?

Can I create a plot legend which doesn't have plotting symbols and that the text itself is fitted to the border box?

例如,在以下代码中,我要删除的图例文本前有一个空格:

For example, in the following code there is a gap before the legend text that I want to get rid of:

plot(c(1,2,3),c(1,1,1))
abline(v=c(1.5,2,2.5),col=c("blue","red","green"))
legend("topright",legend=c("legend 1","legend 2","legend 3"),text.col=c("blue","red","green"))

推荐答案

可以尝试的方法:

# draw your legend without the border and with the text left-aligned and save the components :
myleg<-legend("topright",legend=c("legend 1","legend 2","leg 3"),text.col=c("blue","red","green"),plot=T,bty="n")

# get the user coordinates to adjust the gap between the text and the border
coord<-par("usr")

# add a border, closer to the text (here, gap between border and beginning of text is a hundredth of the plot width) :
rect(myleg$text$x[1]-diff(coord[1:2])/100,myleg$rect$top-myleg$rect$h,myleg$rect$left+myleg$rect$w,myleg$rect$top)

如果要将文本移到绘图的中间,可以使用inset参数(例如:inset = 0.05):

If you want to move the text further towards the middle of the plot, you can use inset parameter (eg: inset=0.05) :

myleg<-legend("topright",legend=c("legend 1","legend 2","leg 3"),text.col=c("blue","red","green"),plot=T,inset=0.05,bty="n")
coord<-par("usr")
rect(myleg$text$x[1]-diff(coord[1:2])/100,myleg$rect$top-myleg$rect$h,myleg$rect$left+myleg$rect$w,myleg$rect$top)

这篇关于如何在不绘制符号的情况下在R中绘制图例并仍然使其对齐良好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆