I am trying to plot multiple y values vs a single x value. I want the graphs to be in seperate figures. The following code is working to generate the graphs, but the y axes are labeled "taxonomy_metadata_combined_p21[,i]" and I want them to have the same labels as the column titles. I have tried multiple different things but how can I change the y axes label?
for(i in 2:ncol(taxonomy_metadata_combined_p21)) {
print(ggplot(taxonomy_metadata_combined_p21, aes(x = Txt_Sex, y = taxonomy_metadata_combined_p21[ , i]))
geom_boxplot())
ylab(colnames(taxonomy_metadata_combined_p21)[i])
}
CodePudding user response:
Your ylab()
was added after the print()
function. If you print after adding ylab()
it should work.
As a sidenote; it is not recommended to use y = taxonomy_metadata_combined_p21[ , i]
as an aesthetic. The ggplot2 authors instead recommend to use the .data
pronoun if the column name is known.
Reprex with built-in data:
library(ggplot2)
df <- rev(iris)
for (i in 2:ncol(df)) {
p <- ggplot(df, aes(x = Species, y = .data[[colnames(df)[i]]]))
geom_boxplot()
ylab(colnames(df)[i])
print(p)
}