0

I want a function to return 2 charts side by side:

GraficosKMeans <- function(dados){ 
  g1 <- ggplot(dados, aes(x = cluster, y = ValorMedio))+
    geom_col()

  g2 <- ggplot(dados, aes(x = cluster, y = FrequenciaMedia))+
    geom_col()
  
  par(mfrow=c(1,2))
  # also tried layout(matrix(c(1,2), 1, 2))

  return(list(g1, g2))
 # also tried g1
 # also tried g2


}

Calling this function with:

GraficosKMeans(dados)

Is returing the charts separately. Why is the plotting area not set into a 1*2 array?

1 Answers1

1

Try this solution using patchwork:

library(patchwork)
library(tidyverse)
#Code
GraficosKMeans <- function(dados){ 
  g1 <- ggplot(dados, aes(x = cluster, y = ValorMedio))+
    geom_col()
  
  g2 <- ggplot(dados, aes(x = cluster, y = FrequenciaMedia))+
    geom_col()
  
  #Compose plot
  g3 <- g1|g2
  
  return(g3)
}

GraficosKMeans(dados)

enter image description here

Duck
  • 39,058
  • 13
  • 42
  • 84