7

I am trying to make plots in a loop. But how do I put different titles on each plot? In this example, I want different names for my 8 density plots, such as beta[Treatment], beta[Time Dummy], etc. Thanks!

par(mfrow=c(4,2)
for (i in 2:8) {
  plot(density(beta[,i]))
  title(main=substitute(paste('Density of ', beta[Treatment]))))
}
Heisenberg
  • 8,386
  • 12
  • 53
  • 102

2 Answers2

11
tvec <- c("Treatment", "Time Dummy")

par(mfrow=c(2,1))
for(i in 1:2){
    plot(density(beta[,i]), 
         main=substitute(paste('Density of ', beta[a]), list(a=tvec[i])))
    }

Or actually if the name of your subscripts is the name of the columns of beta:

par(mfrow=c(4,2))
for(i in 2:8){
    plot(density(beta[,i]), 
         main=substitute(paste('Density of ', beta[a]), list(a=colnames(beta)[i])))
    }
plannapus
  • 18,529
  • 4
  • 72
  • 94
0

If the title is being picked from a column in a dataframe,

        V1  V2
    1   Title1  AA
    2   Title2  BB
    3   Title3  CC
    4   Title4  DD
    5   Title5  EE

The following code can be used to get different titles in the plot:

    num.plots <- nrow(df)
    for(i in 1:num.plots){
      plot(df$V2~df$V3, main=df$V1[i], type = "l", col="red")
      }
kirancodify
  • 695
  • 8
  • 14