Stacked histogram with bivariate colored bars in R

Wednesday, March 22nd, 2017 | Author:

Stacked histogram in R

A histogram gives you counts of elements within spefic ranges of a variable, represented as bars. Sometimes, you want to see more then bars. The following code allows you to represent a second variable with a color shade:

library(ggplot2)
library(data.table)
 
# create an example of a table
d <- data.table(
slope = round(rnorm(50),50),
p = sample(1:50,50)/1000
)
 
# discretize continuous values
d$midp <- floor(d$p*100)/100
d$midslope <- floor(d$slope*10)/10
d$midp <- factor(as.character(d$midp))
 
# reverse the order of the factor 
# to have 0 at the bottom of the scale
d$midp <- factor(d$midp, levels = rev(levels(d$midp))) 
 
# plot your stacked histogram
ggplot(d, aes(x=midslope,fill=midp)) +
geom_bar() +
scale_fill_brewer()
Cite as: André Ourednik (2017) « Stacked histogram with bivariate colored bars in R » in Maps and Spaces from https://ourednik.info/maps/2017/03/22/stacked-histogram-with-bivariate-colored-bars-in-r/ [Last-seen December 11th 2017].