0

I have data of 6 variables in excel (each variable in one column). But the length of each column is different. I want to plot this data by par(mfrow=c(3,2)) to divide the plot in 6 parts and plot all plots together ,but using the name of variable for each graph like the pic I attached. The variable names are: MKT SMB HML RMW CMA MOM And the plot code is

MEplot(S,main = "variable name",cex.main=2,bty="n",cex.axis = 1.3,xlab = "", ylab = "")

I can plot the same photo, but I have to repeat code 6 times because the column name is different, so each time I have to specified the range of column and repeat the code. Could you please help? How can I plot this graph with one code using for loop?

enter image description here

John Polo
  • 547
  • 1
  • 8
  • 25
Neda Fathi
  • 13
  • 4
  • Are you actually using a function called `MEplot()`? We can’t tell because you didn’t include enough information for a [minimum reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). As the link suggests, you should always provide any other `library()` that is part of your code. – John Polo Dec 17 '22 at 11:07

2 Answers2

1

Here's one approach using base R:

  1. Set the plot parameters:

    par(mfrow = c(2,3))
    
  2. Perform for loop for each variable:

    for(i in 1:6){
      plot(df[,i], main = names(df)[i], add = TRUE)
    }
    

Refine plot parameters as needed inside the for loop. If you want to have same-scaled y-axes, use ylim = range(df).

enter image description here

Here's another approach using ggplot2 (has the advantage that the y-scales are automatically aligned)

library(ggplot2)
df %>%
  pivot_longer(everything()) %>%
  ggplot(aes(x = "", y = value)) + 
  geom_point() +
  facet_grid(~ name)

If you want your 2 by 3 layout use facet_wrap(~ name, nrow = 3)(thanks to @r2evans!) enter image description here

Data:

df <- data.frame(
  MKT = rnorm(100),
  SMB = rnorm(100,2),
  HML = rnorm(100,5),
  RMW = rnorm(100,60),
  CMA = rnorm(100,33),
  MOM = rnorm(100,100)
)
Chris Ruehlemann
  • 20,321
  • 4
  • 12
  • 34
  • 1
    Since you're introducing `ggplot2` here, a more representative example (mimicking the original `3x2` plot) could be `facet_wrap(~ name, nrow = 3)`. – r2evans Dec 17 '22 at 12:09
0

Using lapply.

par(mfrow=c(3, 2))
lapply(names(dat), \(x) plot(dat[[x]], main=x, xlab='', ylab='', ylim=range(dat)))

If you want to fill the layout column-wise, use mfcol= isntead of mfrow=. The ylim=range(dat) cares for the y axes to be in the same range.


Data:

set.seed(42)
dat <- setNames(as.data.frame(replicate(length(x), rnorm(100))), c("MKT", "SMB", "HML", "RMW", "CMA", "MOM"))
dat[] <- lapply(dat, sort)

enter image description here

Alternatively to par you can use a layout matrix.

layout(matrix(1:6, ncol=2, byrow=TRUE))
lapply(names(dat), \(x) plot(dat[[x]], main=x, xlab='', ylab='', ylim=range(dat)))
jay.sf
  • 60,139
  • 8
  • 53
  • 110