0
votes

I have a dataframe called test2 and I would like to make multiple plots or subplots which have the same x axis that is month variable and other variables in this dataframe, each as y axis in a plot. My codes is below and it gives me error message... Can you help see how to fix it? Thank in advance.

plot_analysis <- list()

col<-names(test2)[!names(test2)%in%"month"]
for(i in col){
  print(i)
  plot_analysis[i] <- ggplot(data=test2, aes(month))+
    geom_bar(aes(fill=as.factor(col), position="fill")) +
    xlab("month") + ylab("") + scale_y_continuous(labels=scales::percent) + scale_x_discrete(limits = month.abb)
}

Warning messages: 1: Ignoring unknown aesthetics: position 2: In plot_analysis[i] <- ggplot(data = test2, aes(month)) + geom_bar(aes(fill = as.factor(col), : number of items to replace is not a multiple of replacement length

1
One of the problems is that you have position as an aesthetic. It shouldn't be. Move it to after the aesthetics. And then you need to use col as {{col}}Richard Telford
@RichardTelford I think you are right... but didnt get what you mean by "after the aesthetics"... how else can i tell R to make stacked bar plot using col (the variable to be looped) as the indicator of size/color in each bar?user8330379

1 Answers

0
votes

I don't have your data but I did an example.

library(tidyverse)
#library(dplyr)
#library(purrr) # has the map I used to keep functional programming 

colnames(mtcars) %>% 
  map(function(x) mtcars %>% 
    ggplot(aes(carb)) + 
    geom_bar(aes(fill=x, position="cyl"))) 

for loop need a print

for (i in colnames(mtcars)) { 
  print(
    mtcars %>% 
      ggplot(aes(carb)) + 
      geom_bar(aes(fill=i, position="cyl"))
  ) 
}