How to superimpose bar plots in R?

前端 未结 2 465
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 06:12

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

相关标签:
2条回答
  • 2021-01-17 06:42

    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)
    
    0 讨论(0)
  • 2021-01-17 07:07

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

    0 讨论(0)
提交回复
热议问题