I have generated 3 bar plots using barplot() function. Now I need to combine these 3 plots in a single column and get another new plot. I have used cowplot to do so however it showed warning message
In as_grob.default(plot) :Cannot convert object of class matrixarray into a grob.
I know it is easier with ggplot. But I find it hard to write this code in ggplot. Can someone please give me a solution? I am not an expert but I tried my best but could not find a solution. My code:
k <- readr::read.csv("maxcor_r_p.csv", TRUE, ",")
cols <- c("azure3", "#003f5c")[(k$p < 0.05) 1]
maxi <- barplot(
k$r,
names.arg = k$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("T"[max]),
las = 2
)
l <- readr::read.csv("meancor_r_p.csv", TRUE, ",")
cols <- c("azure3", "#27e52a")[(l$p < 0.05) 1]
meany <- barplot(
l$r,
names.arg = l$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("T"[mean]),
las = 2
)
m <- readr::read.csv("precipcor_r_p.csv", TRUE, ",")
cols <- c("azure3", "#27bac6")[(m$p < 0.05) 1]
preci <- barplot(
m$r,
names.arg = m$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("Precipitation"),
las = 2
)
cowplot::plot_grid(
maxi, meany, preci,
ncol = 1, align = "v", axis = 1
)
CodePudding user response:
The reason that cowplot is giving you the conversion error is because it is expecting a ggplot object, so you'd have to rewrite your code in ggplot if you wanted to use cowplot.
You should be able to combine the plots you've created by using the function par(mfrow = c(A, B)
. par()
is a function for setting graphical parameters, and mfrow
is a vector, with the first argument (A) referring to the number of rows you want in the graphic you are creating and the second argument (B) referring to the number of columns you want.
If you want the plots to be displayed in a single column, you could do the following:
# specify a graphic with three rows and one column
par(mfrow = c(3, 1))
# first plot
maxi <-
barplot(
k$r,
names.arg = k$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("T"[max]),
las = 2
)
# second plot
meany <-
barplot(
l$r,
names.arg = l$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("T"[mean]),
las = 2
)
# third plot
preci <-
barplot(
m$r,
names.arg = m$parameter,
ylab = "Correlation coefficient",
col = cols,
main = expression("Precipitation"),
las = 2
)
# reset parameters to default
dev.off()
If you wanted them to be displayed in a single row instead, you would just change your par()
function to:
# specify a graphic with one row and three columns
par(mfrow = c(1, 3))