MNU
MNU

Reputation: 764

How to add the math expression title in multiple plots according to the column name of data set in R?

keep.beta
  beta_0 C1   beta_1 C1     beta_2 C1 beta_0 C2 beta_1 C2    beta_2 C2 beta_0 C3  beta_1 C3    beta_2 C3
1  6.118431  0.14186598 -8.898830e-04  6.022789 0.2284664 -0.008715484  6.362422  0.1623198 -0.007603638
2  6.063539  0.13401758  5.027927e-06  5.986915 0.2469357 -0.009225261  6.150559  0.2002901 -0.007515155
3  6.193407  0.05483201  6.126576e-03  5.841100 0.3347416 -0.016506298  7.146271 -0.3979893  0.041127363
4  6.078092  0.05110730  6.354140e-03  5.562972 0.4690519 -0.027162758  8.179671 -1.0250484  0.089065099
5  6.256228 -0.09785900  1.856215e-02  5.644385 0.4701571 -0.027528102  8.394842 -1.2646359  0.106934875
  beta_0 C4   beta_1 C4    beta_2 C4
1  6.097189  0.16624813 -0.004341827
2  6.164902  0.09360776  0.002282821
3  6.211754  0.03602315  0.007230330
4  6.505551 -0.10780312  0.016602683
5  6.692843 -0.24754950  0.028275593

To plot each column separately, I am using the following loop,

loop.vector=1:ncol(keep.beta)
  #plot for betas
  for(b in loop.vector) {
    x.beta<-keep.beta[,b]
    plot(x.beta, type = "l", main=colnames(keep.beta)[b], ylab="") 
    mtext("beta plot",line=-1.5, cex=1.5, outer = TRUE)
    }

All the title comes as beta_0 C1 , beta_1 C1 and so on. How can I replace all the betas in the title by math notation beta?

Upvotes: 0

Views: 158

Answers (1)

Edward
Edward

Reputation: 19219

You'll need regular expressions to extract the betas and the Cs. Then use bquote with variables .() to plot them. This is similar to expression() but more flexible. And the mtext can go outside the loop.

op <- par(mfrow=c(2,3))
for(b in loop.vector) {
  x.beta <- keep.beta[,b]
  beta <- substr(sub("^beta_", '', names(keep.beta)[b]),1,2)
  Cn <- sub("^\\S+\\s+", '', names(keep.beta)[b] )
  plot(x.beta, type = "l", main=bquote(beta[.(beta)]~.(Cn)), ylab="") 
}
mtext("beta plot",line=-1.5, cex=1.5, outer = TRUE)
par(op)

enter image description here

Data:

keep.beta <- data.frame(1:5, 2:6, 3:7, 4:8, 5:9, 6:10)
names(keep.beta) <- c("beta_0 C1","beta_1 C1","beta_2 C1",
                      "beta_0 C2","beta_1 C2","beta_2 C2")

Upvotes: 2

Related Questions