Quinten
Quinten

Reputation: 41603

For looping x-as in ggplot

I would like to create multiple histograms (ggplot) using a for loop. The problem is that my x-as from the plots, stay the same like "value". Do you know how to change the x-as every time it loops?

My dataframe for example:

df <- data.frame(variable = c("A", "A", "B", "B", "C", "C"), value = c(1, 2, 4, 5, 2, 3))

So that means I get three plots with x-as: "A", "B" and "C"

My code:

for (i in unique(df$variable)){
d <- subset(df, df$variable == i)
  print(ggplot(d, aes(x = value)) + geom_histogram())
}

Upvotes: 0

Views: 111

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389335

You can take help of imap to get different x-axis value after splitting the data by variable.

library(ggplot2)

list_plot <- df %>%
              split(.$variable) %>%
              purrr::imap(~ggplot(.x, aes(x = value)) + 
              geom_histogram() + xlab(.y))

Also have you considered using facets? Where x-axis is the same and you get A, B, C as facet names.

ggplot(df, aes(x = value)) + geom_histogram() + facet_wrap(~variable)

Upvotes: 1

Related Questions