在单个图例中设置多种大小的文本

时间:2014-06-11 19:14:16

标签: r plot legend

我尝试在单个图例中设置多种尺寸的文字。

plot(1, 1)
legend("topleft", 
       legend=c("fruit", "apples", "oranges", "vegetables", "cucumber", "peppers"), 
       cex=0.8,
       pch=c(19, NA, NA, 19, NA, NA),
       col=c("red", "white", "white", "green", "white", "white"), 
       pt.cex=1)

legendallsamesize

我喜欢"苹果," "桔子," "黄瓜,"和"辣椒"要小一些。

我可以通过以下方式设置不同大小的点:

plot(1, 1)
legend("topleft", 
       legend=c("fruit", "apples", "oranges", "vegetables", "cucumber", "peppers"), 
       cex=0.8,
       pch=c(19, NA, NA, 19, NA, NA),
       col=c("red", "white", "white", "green", "white", "white"), 
       pt.cex=c(1, NA, NA, 0.8, NA, NA))

但是如果我尝试以类似的方式设置文本大小,我会收到警告,并以奇怪的方式创建两次图例。

plot(1, 1)
legend("topleft", 
       legend=c("fruit", "apples", "oranges", "vegetables", "cucumber", "peppers"), 
       cex=c(1, 0.8, 0.8, 1, 0.8, 0.8),
       pch=c(19, NA, NA, 19, NA, NA),
       col=c("red", "white", "white", "green", "white", "white"), 
       pt.cex=c(1, NA, NA, 0.8, NA, NA))

badlegend

我很确定我的问题源于不了解传奇人物对cex的要求。我也意识到我可能会拨打legend()两次,并使用text()来插入我的文字,但这似乎很费时间。

1 个答案:

答案 0 :(得分:3)

如果您在图例调用中提供多个cex值,它会为每个(唯一的?)cex值绘制一个图例。

正如@MrFlick建议的那样,您可以使用不同的字体来创建层次结构。这是使用文本的解决方案。通过将图例调用的输出写入a,我们可以轻松地重复使用文本标签的计算位置,并在不同的点数中添加文本,只需添加一行:

plot(1, 1)

labs = c("fruit", "apples", "oranges", "vegetables", "cucumber", "peppers")

# add legend with white (invisible text) and store text positions in 'a'
a=legend("topleft", 
       legend=labs, 
       cex=1.0,
       text.col='white',
       pch=c(19),
       col=c("red", "white", "white", "green", "white", "white"))

# draw text labels at calculated positions
text(a$text$x, a$text$y, lab=labs, cex=c(1, 0.8, 0.8, 1, 0.8, 0.8), pos=4, offset=c(0,0.1))