filod filod - 1 month ago 19
R Question

Histogram of counts with faceting ggplot2

Let's say I have the following data frame

category = c( "A", "B", "C", "B", "A", "B")
Jan.10 = c(20,10,30,20,15,46)
Feb.10 = c(10,10,40,20,25,46)
Mar.10 = c(40,10,80,20,25,56)
Jan.11 = c(50,10,20,20,45,56)
Feb.11 = c(70,10,30,20,35,46)
Mar.11 = c(60,10,50,20,25,66)
df <- data.frame(category, Jan.10, Feb.10, Mar.10, Jan.11, Feb.11, Mar.11)


How do I create a three histograms by faceting, one for each category, with months on the x-axis and counts on the y-axis?
Something like this I am trying to get:
example-image

This is my best attempt so far:

df_melt <- df %>% melt()
df_melt$variable <- as.yearmon(df_melt$variable, "%b.%y")

ggplot(df_melt, aes(x=variable)) +
geom_histogram() +
xlab("Year and Month") +
ylab("Sales") +
facet_grid(category ~.) +
theme_bw()


But it isn't working right.

Any help would be much appreciated!

Answer

I think you want something like this:

df_melt <- df %>% melt()
df_melt$variable <- as.yearmon(df_melt$variable, "%b.%y") 

ggplot(df_melt, aes(x=variable, y=value)) + 
  geom_bar(stat='identity') +
  xlab("Year and Month") +
  ylab("Sales") + 
  facet_wrap(~category, ncol = 1) +
  theme_bw()

enter image description here