I am creating a function that uses a forloop to create and return a list of ggplots. When I try to view any of the returned plots, e.g. by calling plots["aClass_20_30"]
, I get:
Error: StatBin requires a continuous x variable: the x variable is discrete. Perhaps you want stat="count"?
However, if I create one of the plots outside the forloop, as below, it shows up just fine because the variable in question, myVar
, IS continuous:
tpp %>%
filter(risk_class == "aClass", age_buckets=="20_30") %>%
ggplot(aes(x=myVar)) +
geom_area(stat='bin') +
labs(title = paste("aClass", "20_30", sep="_"))
This is the function:
plot_fixed_age_class_against <- function(variable) {
temp <- tpp %>%
select_('age_buckets', 'rclass', variable) %>%
filter(!is.na(rclass))
plots <- vector("list", 48)
for (class in unique(temp$rclass)) {
for (age in unique(temp$age_buckets)) {
print(paste(class, age, sep="_"))
plots[[paste(class, age, sep="_")]] <-
temp %>%
filter(rclass == class, age_buckets==age) %>%
ggplot(aes(x=variable)) +
geom_area(stat='bin') +
labs(title = paste(class, age, sep="_"))
}
}
#print(plots)
return(plots)
}
and I call it using plots <- plot_fixed_age_class_against("myVar")
If I change bin to count within the forloop, the graphs show up but there is nothing plotted on them. However, using bin outside the forloop, as above, works perfectly. myVar
is numeric.