How to superimpose bar plots in R?

こ雲淡風輕ζ 提交于 2020-01-03 05:38:07

问题


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.

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.


回答1:


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)



回答2:


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))



来源:https://stackoverflow.com/questions/34204198/how-to-superimpose-bar-plots-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!