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?
CodePudding user response:
Here's one approach using base R
:
Set the plot parameters:
par(mfrow = c(2,3))
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)
.
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!)
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)
)
CodePudding user response:
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)
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)))