Home > Software engineering >  how to set dual Y axis in geom_bar plot in ggplot2?
how to set dual Y axis in geom_bar plot in ggplot2?

Time:01-20

I'd like to draw bar plot like this but in dual Y axis

(enter image description here

A second but similar option would be to use ggh4x which via ggh4x::facetted_pos_scales allows to set the limits for facet panels individually. One drawback, the panels have the same width. (I failed in making this approach work with facet_grid and space="free")

library(ggplot2)
library(ggh4x)

data$facet <- data$index %in% "PBIAS"

ggplot(data, aes(x = index, y = value, fill = period))  
  geom_bar(position = "dodge", stat = "identity")  
  geom_errorbar(aes(ymin = value - sd, ymax = value   sd),
    position = position_dodge(0.9), width = 0.2, alpha = 0.5, size = 1
  )  
  facet_wrap(~facet, scales = "free")  
  facetted_pos_scales(
    y = list(
      facet ~ scale_y_continuous(limits = c(-15, 15), position = "right"),
      !facet ~ scale_y_continuous(limits = c(0, 1), position = "left")
    )
  )  
  theme_bw()  
  theme(strip.text.x = element_blank())

enter image description here

  • Related