Hello there I hope you are haveing a nice day, currently i'm writing a simple function to make some bar plots and histograms but no matter what I do, the NA keep appearing in the plot, i've tried filtering, and using the geom argument for na.rm but I don't really know why the NA keep showing in the bar plots
plot_dataframe <- function(df, df_name, nbin){
#Create empty list to store plots
plots <- list()
#Loop through each variable in the dataframe
for(var in names(df)){
#Check if variable is a factor or numeric
if(is.factor(df[[var]])){
# Create bar plot using ggplot2
plot <- ggplot(df, aes(x = df[[var]])) + geom_bar(stat="count", width=0.5, fill="steelblue", colour="black", na.rm = TRUE) +
geom_text(stat='count', aes(label=..count..), vjust= 0, hjust = 0, , na.rm = TRUE) +
# Use the `label` function to get the label of `x` as the plot title
labs(y = label(df[[var]]), x= NULL)
# Check if variable has more than 6 levels
if(length(levels(df[[var]])) > 6){
# Use coord_flip() to flip axes
plot <- plot + coord_flip()
}
# Add plot to list
plots[[var]] <- plot
# Save plot to folder
ggsave(paste0("plots/", df_name, "/", var, ".png"), plot)
} else if(is.numeric(df[[var]])){
# Create histogram using ggplot2
plot <- ggplot(df, aes(x = df[[var]])) + geom_histogram(aes(y=stat(count)), colour="black", fill="steelblue", bins = nbin ) +
# Use the `label` function to get the label of `x` as the plot title
labs(x=label(df[[var]]))
# Add plot to list
plots[[var]] <- plot
# Save plot to folder
ggsave(paste0("plots/", df_name, "/", var, ".png"), plot)
}
}
}