-1

I want to generate a facet plot of histograms of all variables, but each histograms should be colored by a group. For example, using mtcars, I want to get a facet plot of histograms of all variables colored by am. I can create a single colored histogram as shown below:

library(ggplot2)
ggplot(mtcars, aes(mpg, fill=factor(am))) + 
  geom_histogram(aes(y=..density..), alpha=0.6, position="identity")

I see here how to get a facet plot of histograms, but these aren't colored. How can I do both?

Gaurav Bansal
  • 5,221
  • 14
  • 45
  • 91
  • 2
    Usually, whenever I hear *"plot something by-column in `ggplot2`"*, my first reaction is to convert the data from "wide to long", where column-name is stored in one column, and column-value is stored in another ... and then facet on the column-name (as @kath's answer does). This is not always right, however, as it combines all values into one column, coercing all contents into one class (integer, numeric, or character). At best, this means your logicals are shown as 0 and 1, but if any of your values are categorical, there-be-problems. – r2evans Jul 31 '19 at 15:39
  • 1
    (If you have categorical data in *one or more* of the columns, you would likely have to resort to two different `gather`s, then `*_join` them together where you'd have `num_value` column from the numeric columns, `disc_value` from the categorical columns, and each would be `NA` for the other (i.e., `all(xor(is.na(num_value),is.na(disc_value)))` is true). – r2evans Jul 31 '19 at 15:44

1 Answers1

2

You can gather the data.frame without the variable you'd like to color by.

library(ggplot2)
library(tidyr)

ggplot(gather(mtcars, key, value, -am), aes(value, fill = factor(am))) + 
  geom_histogram(aes(y = ..density..), alpha = 0.6, position = "identity") + 
  facet_wrap(~key, scales = 'free_x')

enter image description here

kath
  • 7,624
  • 17
  • 32