1

I'm trying to create a figure similar to the one below (taken from Ro, Russell, & Lavie, 2001). In their graph, they are plotting bars for the errors (i.e., accuracy) within the reaction time bars. Basically, what I am looking for is a way to plot bars within bars.

stacked bar chart

I know there are several challenges with creating a graph like this. First, Hadley points out that it is not possible to create a graph with two scales in ggplot2 because those graphs are fundamentally flawed (see Plot with 2 y axes, one y axis on the left, and another y axis on the right)

Nonetheless, the graph with superimposed bars seems to solve this dual sclaing problem, and I'm trying to figure out a way to create it in R. Any help would be appreciated.

Community
  • 1
  • 1
stasSajin
  • 144
  • 1
  • 1
  • 7
  • 1
    Please consider reading up how to produce a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Include what you've tried yourself. Note that double-yaxis are generally considered a bad idea. – Heroka Dec 10 '15 at 14:22
  • 1
    for the superimposed bars you could use something like that ggplot(data=mtcars, aes(x=factor(cyl))) + geom_bar(width=.5) + geom_bar(data=mtcars2, aes(x=factor(cyl)), width=.2, color="lightblue") – MLavoie Dec 10 '15 at 14:27

2 Answers2

4

It's fairly easy in base R, by using par(new = T) to add to an existing graph

set.seed(54321) # for reproducibility

data.1 <- sample(1000:2000, 10)
data.2 <- sample(seq(0, 5, 0.1), 10)

# Use xpd = F to avoid plotting the bars below the axis
barplot(data.1, las = 1, col = "black", ylim = c(500, 3000), xpd = F)
par(new = T)
# Plot the new data with a different ylim, but don't plot the axis
barplot(data.2, las = 1, col = "white", ylim = c(0, 30), yaxt = "n")
# Add the axis on the right
axis(4, las = 1)
nico
  • 50,859
  • 17
  • 87
  • 112
  • Thanks Nico. Do you know of a way of aligning the bars properly after changing their width? For instance, I plot the second bar with space=1, as in `barplot(data.2, las = 1, col = "white", ylim = c(0, 30), yaxt = "n", space=1)`, but the bars don't fall right in the middle. – stasSajin Dec 10 '15 at 14:37
  • @stasSajin indeed that's true, not quite sure how to fix that though, sorry – nico Dec 10 '15 at 17:59
4

It is pretty easy to make the bars in ggplot. Here is some example code. No two y-axes though (although look here for a way to do that too).

library(ggplot2)
data.1 <- sample(1000:2000, 10)
data.2 <- sample(500:1000, 10)

library(ggplot2)
ggplot(mapping = aes(x, y)) +
  geom_bar(data = data.frame(x = 1:10, y = data.1), width = 0.8, stat = 'identity') +
  geom_bar(data = data.frame(x = 1:10, y = data.2), width = 0.4, stat = 'identity', fill = 'white') +
  theme_classic() + scale_y_continuous(expand = c(0, 0))

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94