How to only make one legend name italic in base R plot?

。_饼干妹妹 提交于 2019-12-19 10:17:40

问题


I want to add a legend to a plot in which only one of the legend names is italicized. I'm using plot() in base R.

  • However, I need that italicized line to contain variable numbers, so I use bquote.

What I've tried does not work:

  a <- 2 ; b <- 5
  plot(a,b)
  l1 <- bquote(Italic ~ .(a) + .(b))
  l2 <- bquote(a + b)
  legend(x='topright',legend = bquote(italic(.(l1))))
  legend(x='topleft',legend = c(bquote(italic(.(l1))),l2))
  • Notice that when I leave the expression on its own (RIGHT LEGEND), it italicizes correctly. However, when I add the text for other legend lines, it messes up (LEFT LEGEND).

How do I properly do this?

Note: I'd rather have a solution that doesn't require multiple calls to legend().


回答1:


You could use text.font = 3, say:

legend(x='topleft',legend = c(bquote((.(l1))),l2), text.font=c(3,1))



回答2:


You should use as.expression to coerce everything into an expression object.

a <- 2
b <- 5
plot(a,b)
legend("topleft", legend = c(as.expression(bquote(italic("Italic: "*.(a)*" + "*.(b)))),
    as.expression(bquote("Non Italic: "*.(a)*" + "*.(b)))) )

To modify your example

a <- 2
b <- 5
plot(a,b)
l1 <- bquote(Italic ~ .(a) + .(b))
l2 <- bquote(a + b)
legend("topleft", legend =  c(as.expression(bquote(italic(.(l1)))),
                            as.expression(bquote(.(l2))) ))


来源:https://stackoverflow.com/questions/43079533/how-to-only-make-one-legend-name-italic-in-base-r-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!