1
votes

I'm trying to loop through every column of the iris data set and plot a histogram in ggplot. So I'm expecting 5 different histograms to appear. However, my for loop below returns nothing. How can I fix this?

library(ggplot2)

for (i in colnames(iris)){
  ggplot(iris, aes(x = i))+
    geom_histogram()
}
2
There is no need to load the entire tidyverse if the goal is to only use ggplot(2) - NelsonGon
If you really want to do this with a for loop you might have to to use aes_string instead of aes. But for getting the desired results i think @Maurits Evers answer is the better approach :) - TinglTanglBob

2 Answers

2
votes

Instead of using a for loop, the tidyverse/ggplot way would be to reshape the data from wide to long and then plot using facet_wrap

library(tidyverse)
iris %>%
    gather(key, val, -Species) %>%
    ggplot(aes(val)) +
    geom_histogram(bins = 30) +
    facet_wrap(~key, scales = "free_x")

enter image description here

1
votes

Using dplyr, tidyr and ggplot:

library(ggplot2)
library(dplyr)
library(tidyr)

iris %>% 
  gather(Mesure, Value, -Species) %>%
  ggplot(aes(x=Value)) + geom_histogram() + facet_grid(rows=vars(Species), cols=vars(Mesure))

Result: enter image description here