Wednesday, October 29, 2008

Plotting Math in R

Plotting math in R can be acheived using the expression(). To know detailed usage, in R console,

demo(plotmath)

But expression() is not flexible when you want to plot math symbols and parameters altogether. In this case, we use bquote() which is actually a wraper for substitute() and quote(). It has the ability to do paste() and expression() altogether. Here is a simple example.

k <- 2
plot(1, main=bquote(y[i][","][j]~"= "*.(k)))

Note, ".()" evaluates whatever inside the parenthesis. In the expression() and bquote(), "~"means a single-bye space. To bind two expression together without space, use "*" instead.

6 comments:

Anonymous said...

Shouldn't it be ... k))) You missed out a (closing) bracket.

Yu-Sung Su said...

Thank you! Revised!

RENU said...

哈囉!
我是你表弟瑞霖!
我現在是讀統計所,
發現哥哥的網誌有很多R的文章,
剛好我現在也正在學習R,
以後有問題可以問你嗎?
謝謝!

Yu-Sung Su said...

嗨!表弟!

沒問題!

RENU said...

哥哥你好:
我想請問你R中 plot 的指令,
例如:
plot(rnorm(10))
plot(rt(10, df=1), col=2)
如何將兩個圖形合併在一張圖上呢?
沒辦法使用 add=TRUE ,
這指令是什麼時候可以使用呢??
謝謝
瑞霖

Yu-Sung Su said...

瑞霖,

plot(rnorm(10))
points(rt(10, df=1), col=2)

plot()在R是高階繪圖程式,所以大部分的時候的使用plot都會開啟一張新的圖面,如果你想要在一個高階繪圖程式所繪圖面再加上其他繪圖物件,你就必須用相對低階的程式,例如:lines(), abline(), curve(), points(), segments(), text(), 等等. 如以上例子!