GRowInG
GRowInG

Reputation: 658

How to set column names as histogram titles in ggplot2

I would like to draw multiple histograms from the iris dataset using ggplot2. The only thing that is missing is an elegant way to set the column names from that dataset as titles for each plot in labs (title = ). I previously tried to use colnames and paste in multiple ways, however, that did not return the desired output. Has anyone of you an idea how to get this final step done so that each histogram shows the corresponding column name as title?

Here's my reprex:

library (ggplot2)

# Reorder iris columns for convenience
df <- iris[,c(5, 1:4)]
 
# Histograms - z represents the columns of the df containing data for histograms
 histograms <- apply (df[,2:ncol(df)], 2, function (z){
     ggplot(df, aes(x = z)) +
       geom_histogram(aes(y = ..density..)) + 
       stat_function(fun = dnorm, args = list(mean = mean(z, na.rm =TRUE), sd = sd(z, na.rm = TRUE)), colour = "blue") +
       facet_wrap(~ Species) +
       labs (title = "Histogram for column z", x = "values")
  })

histograms

Upvotes: 2

Views: 826

Answers (1)

stefan
stefan

Reputation: 124183

Try this. Instead of iterating over the columns iterate over the names:

library (ggplot2)

# Reorder iris columns for convenience
df <- iris[,c(5, 1:4)]

# Histograms - z represents the columns of the df containing data for histograms
histograms <- lapply (names(df[,2:ncol(df)]), function (z){
  mean <- mean(df[[z]], na.rm =TRUE)
  sd <- sd(df[[z]], na.rm =TRUE)
  ggplot(df, aes(x = !!sym(z))) +
    geom_histogram(aes(y = ..density..)) + 
    #stat_function(fun = dnorm, args = list(mean = mean(z, na.rm =TRUE), sd = sd(z, na.rm = TRUE)), colour = "blue") +
    stat_function(fun = dnorm, args = list(mean = mean, sd = sd), colour = "blue") +
    facet_wrap(~ Species) +
    labs (title = paste0("Histogram for column ", z), x = "values")
})

histograms[[1]]
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

Created on 2020-06-20 by the reprex package (v0.3.0)

Upvotes: 1

Related Questions