rggplot2geom-bar

different colors for geom_bar and geom_jitter


I am trying to create a plot where geom_bar represents the mean of a set of data points and the individual data points are shown using geom_jitter. I'd like for the bar graphs to be colored by factor, but for the individual data points to be white.

This is my script:

ggplot(dataframe, 
       aes(x = `glucose`, y = `CTV dilution factor`, fill = `cellobiose`))+
  geom_bar(stat = "summary", position = "dodge")+
  geom_jitter(position = position_jitterdodge(), 
              shape = 21, stroke=0.5, size=2.5, show.legend = FALSE)+
  ylab("CTV dilution factor")+
  xlab("glucose [mM]")+
  facet_wrap(~condition, ncol=2)+
  theme_manish()+
  theme(text=element_text(size=16))

result

As you can see, the bars and jitter points are filled with the same color. I'd like to keep the colors on the bars, but for the jitter points to be filled with white.

Any suggestions? Thanks!


Solution

  • The default way to achieve that would be to set fill="white" for the geom_jitter or geom_point and to make use of the group aes, i.e. use group=cellobiose in geom_point to dodge the points by cellobiose. However, when doing so I encountered an error which seems to be a known but still unresolved issue.

    A possible workaround would be to map on the color aesthetic instead and set outline colors to "black" using scale_color_manual.

    Using a minimal reproducibel example based on mtcars:

    dataframe <- mtcars[c("cyl", "mpg", "am", "vs")]
    dataframe[c("cyl", "am", "vs")] <- lapply(dataframe[c("cyl", "am", "vs")], factor)
    names(dataframe) <- c("glucose", "CTV dilution factor", "cellobiose", "condition")
    
    library(ggplot2)
    
    ggplot(
      dataframe,
      aes(x = glucose, y = `CTV dilution factor`, fill = cellobiose)
    ) +
      geom_bar(stat = "summary", position = "dodge") +
      geom_point(aes(color = cellobiose),
        fill = "white",
        position = position_jitterdodge(dodge.width = .9, seed = 1),
        shape = 21, stroke = 0.5, size = 2.5, show.legend = FALSE,
      ) +
      scale_color_manual(values = rep("black", 2)) +
      ylab("CTV dilution factor") +
      xlab("glucose [mM]") +
      facet_wrap(~condition, ncol = 2) +
      # theme_manish() +
      theme(text = element_text(size = 16))
    

    enter image description here