Expression and new line in plot labels [duplicate]

2019-02-06 06:26发布

This question already has an answer here:

I want to add some subscripts and superscripts to my graph labels. I've try expression, but it doesn't work as I wish with new lines (\n). I've try to fix it using paste, but it doesn't work. Below are some of my tries:

par(mfcol=c(1,3))
plot(1,1,main=expression("first line \n second line x"^2))
plot(1,1,main=expression(paste("first line \n second line", "x"^2)))
plot(1,1,main=paste("first line \n second line", expression("x"^2)))

It produces:

enter image description here

In first two pictures the second line is not well centered, in the third one the superscript fails. How to get both centered line and subscripts/superscripts?

2条回答
我命由我不由天
2楼-- · 2019-02-06 07:08

A fast solution is to add some spaces before the word "first".

Since plotmath does not support newlines, you can use mtext to create your lines one by one like this:

plot(1,1)
exp <- 2
Lines <- list(bquote("first line"),bquote("second line x"^2))
mtext(do.call(expression, Lines),side=3,line=1:0)

enter image description here

查看更多
爷、活的狠高调
3楼-- · 2019-02-06 07:29

You can introduce a line break inside an expression:

bquote(atop("first line",
            "second line" ~ x ^ 2))

(I’m using bquote rather than expression here – both work in this case.)

Execute demo(plotmath) for more information and look at the documentation for atop.

boxplot apparently has some trouble interpreting expressions in its title. A simple fix is to plot the title separately:

boxplot(data, main = '')
title(bquote(atop("first line", "second line" ~ x ^ 2)))
查看更多
登录 后发表回答