stasSajin
stasSajin

Reputation: 144

How to superimpose bar plots in R?

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.

Upvotes: 1

Views: 13173

Answers (2)

Axeman
Axeman

Reputation: 35187

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

Upvotes: 4

nico
nico

Reputation: 51640

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)

Upvotes: 4

Related Questions