5

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_?

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

1 Comment

phantom downvoter! state your name and explain yourself!
4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.