Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2, applying two scales to the same plot? Top down barplot

Tags:

r

ggplot2

See plot here:

enter image description here (from here)

How do I reproduce both the upper and lower portion of the barplot using ggplot2?

For example, I can produce the upper portion with

ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + scale_y_reverse()

However now if I add any other geom_, such as another geom_bar() the scale for y is reversed. Is it possible to apply the scale_y_reverse() to only a specific geom_?

like image 971
Vlo Avatar asked Jul 23 '14 17:07

Vlo


2 Answers

Another option is to make two separate plots and combine them with arrangeGrob from the gridExtra package. After playing with the plot margins, you can arrive at something that looks decent.

library(gridExtra)
library(ggplot2)

set.seed(100)
p2 <- ggplot(data.frame(x=rnorm(1000, 5)), aes(x=x)) + geom_bar() + theme(plot.margin=unit(c(0,0,0,0), 'lines'))
p1 <- p2 + scale_y_reverse() + 
    theme(plot.margin=unit(c(0, 0, -.8, 0), 'lines'), axis.title.x=element_blank(), 
          axis.text.x=element_blank(), axis.ticks.x=element_blank())

p <- arrangeGrob(p1, p2)
print(p)

enter image description here

like image 181
Matthew Plourde Avatar answered Oct 13 '22 01:10

Matthew Plourde


ggplot only like to have one y-axis scale. The easiest thing would be to basically reshape your data yourself. Here we can use geom_rect to draw the data where ever we like and we can condition it on group time. Here's an example

#sample data
dd<-data.frame(
  year=rep(2000:2014, 2), 
  group=rep(letters[1:2], each=15), 
  count=rpois(30, 20)
)

And now we can plot it. But first, let's define the offset to the top bars by finding the maxima height at a year and adding a bit of space

height <- ceiling(max(tapply(dd$count, dd$year, sum))*1.10)

And here's how we plot

ggplot(dd) + 
  geom_rect(aes(xmin=year-.4, xmax=year+.4, 
    ymin=ifelse(group=="a", 0, height-count), 
    ymax=ifelse(group=="a", count, height), fill=group)) + 
  scale_y_continuous(expand=c(0,0))

And that will give us

enter image description here

like image 36
MrFlick Avatar answered Oct 13 '22 00:10

MrFlick