Search code examples
rggplot2geom-bar

Align point to corresponding bar in dual axis


Using ggplot, how do I align the geom_point with its corresponding bar and add a black outline to those points. Below is the minimal code and it's output.

temp_mpg <- mpg %>% group_by(year, manufacturer) %>% summarise(displ = first(displ),
                                                               cty = first(cty)) 

coeff <- max(temp_mpg$cty) / max(temp_mpg$displ)

temp_mpg %>% ggplot(aes(x = manufacturer, fill=as.factor(year))) +
  geom_bar( aes(y = displ), 
            stat="identity", position='dodge',
            color="black") +
  geom_point( aes(y = cty / coeff, color = as.factor(year)), 
              size = 4) +
  scale_y_continuous(
    sec.axis = sec_axis(~(.) * coeff)
  ) + 
  theme_minimal() +
  theme(
    axis.text.x = element_text(angle = 90)
  )

Output : enter image description here


Solution

  • You can add a position to your geom_point() for the alignment. For the black outline, set the shape = 21 and then map the variable to the fill.

    temp_mpg %>% ggplot(aes(x = manufacturer, fill=as.factor(year))) +
      geom_bar( aes(y = displ), 
                stat="identity", position='dodge',
                color="black") +
      geom_point( aes(y = cty / coeff, fill = as.factor(year)), 
                  size = 4, shape = 21, position = position_dodge(0.9)) +
      scale_y_continuous(
        sec.axis = sec_axis(~(.) * coeff)
      ) + 
      theme_minimal() +
      theme(
        axis.text.x = element_text(angle = 90)
      )
    

    enter image description here

    As I understood from the documentation a default bar's width is 90% of the data resolution, so probably the 0.9 is a good choice for the dodging width.