简体   繁体   中英

How can I add a y-axis label for each column of the ggplot2?

For example I want to add a log10(Sepal.Width) label on the second column y-axis

data(iris)
iris$Sepal.Width[iris$Species=="versicolor"] <- log10(iris$Sepal.Width[iris$Species=="versicolor"])
p <- iris %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Width)) +
  theme_classic()+
  geom_point()
p+  facet_wrap(~Species,scales = "free")

One option to add titles to each panel (or the only one I'm aware of) would be to create separate plots and glue them together using eg patchwork . To this end I split the data by the facetting variable, use a custom plotting function and finally Map to loop over the splitted data and a vector of axis titles:

library(ggplot2)
library(patchwork)

iris2 <- iris
iris2$Sepal.Width[iris2$Species == "versicolor"] <- log10(iris2$Sepal.Width[iris2$Species == "versicolor"])

plot_fun <- function(.data, y) {
  ggplot(.data, aes(x = Sepal.Length, y = Sepal.Width)) +
    theme_classic() +
    geom_point() +
    facet_wrap(~Species, scales = "free") +
    labs(y = y)
}

y_title <- c("Sepal.Width", "log10(Sepal.Width)", "Sepal.Width")
iris_split <- split(iris2, iris2$Species)

Map(plot_fun, iris_split, y_title) |> 
  wrap_plots()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM