Skip to content

Instantly share code, notes, and snippets.

@geotheory
Last active August 29, 2015 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geotheory/21f65359458743bb2787 to your computer and use it in GitHub Desktop.
Save geotheory/21f65359458743bb2787 to your computer and use it in GitHub Desktop.
ggplot geom_bar: stack and center
require(ggplot2); require(tidyr); require(dplyr)
dat = data.frame(grp=letters[1:3], very_bad=c(4,2,1), bad=c(3,4,2), good=c(2,3,4), very_good=c(1,1,3))
(d = dat %>% tidyr::gather(rating, value, very_bad:very_good) %>%
mutate(rating = ordered(rating, levels=c('very_bad','bad','good','very_good'))))
ggplot() +
geom_bar(data = subset(d, rating %in% c('very_bad','bad')),aes(grp, -value, fill=rating), position="stack", stat="identity") +
geom_bar(data = subset(d, !rating %in% c('very_bad','bad')), aes(grp, value, fill=rating), position="stack", stat="identity") +
scale_fill_manual(values=colorRampPalette(c('red','grey','green'))(4)) +
geom_line(data=NULL, aes(x=c(0.5,3.5),y=0,0), size=1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment