Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you create a bar plot for two variables mirrored across the x-axis in R?

Tags:

graph

plot

r

I have a dataset with an x variable and two y1 and y2 variables (3 columns in total). I would like to plot y1 against x as a bar plot above the axis and y2 against the same x in the same plot underneath the x axis so that the two bar plots mirror each other.

Figure D below is an example of what I am trying to do.

Figure **D**

like image 206
blJOg Avatar asked Aug 09 '11 15:08

blJOg


1 Answers

Using ggplot you would go about it as follows:

Set up the data. Nothing strange here, but clearly values below the axis will be negative.

dat <- data.frame(
    group = rep(c("Above", "Below"), each=10),
    x = rep(1:10, 2),
    y = c(runif(10, 0, 1), runif(10, -1, 0))
)

Plot using ggplot and geom_bar. To prevent geom_bar from summarising the data, specify stat="identity". Similarly, stacking needs to be disabled by specifying position="identity".

library(ggplot2)
ggplot(dat, aes(x=x, y=y, fill=group)) + 
  geom_bar(stat="identity", position="identity")

enter image description here

like image 158
Andrie Avatar answered Oct 08 '22 19:10

Andrie