1
votes

I'm trying to compliment my ggdotchart with the standard deviation from the mean, however, I can not do so in an aesthetically pleasing manner. Therefore I need to change the order of the layers, but I can not get it working.

library(ggpubr)

  # Load data
  data("mtcars")
  dfm <- mtcars
  # Convert the cyl variable to a factor
  dfm$cyl <- as.factor(dfm$cyl)
  # Add the name colums
  dfm$name <- rownames(dfm)


  ggdotchart(dfm, x = "name", y = "mpg",
             color = "cyl",                                # Color by groups
             palette = c("#00AFBB", "#E7B800", "#FC4E07"), # Custom color palette
             sorting = "descending",                       # Sort value in descending order
             add = "segments",                             # Add segments from y = 0 to dots
             rotate = TRUE,                                # Rotate vertically
             group = "cyl",                                # Order by groups
             dot.size = 6,                                 # Large dot size
             label = round(dfm$mpg),                        # Add mpg values as dot labels
             font.label = list(color = "white", size = 9, 
                               vjust = 0.5),               # Adjust label parameters
             ggtheme = theme_pubr()                        # ggplot2 theme
  ) + geom_errorbar(aes(x = name, ymin = mpg - sd(mpg), ymax = mpg + sd(mpg)), position = "identity")

This results in the errorbar over the dots, while I want to have it in behind the dots. I tried to reverse the layers, but couldn't get it working. In normal ggplot it is just changing the order, however, the package makes it difficult to do so.

1
Insert Layer underneath existing layers in ggplot2 object stackoverflow.com/a/20250185/11477907Bruce Schardt

1 Answers

2
votes

While I like the answer in the link, I think it brings a bit of unnecessary complication into play. We can save the plot in whatever order and then change them, instead of concatenating different geoms to our plot.

g$layers[c(4,1,2,3)] -> g$layers

Where g is your plot and the first three layers are from ggdotchart.


For the sake of completion:

If you want to use the solution suggested in the comments it would be:

 g$layers <- c(geom_errorbar(aes(x = name, ymin = mpg - sd(mpg), ymax = mpg + sd(mpg)), 
                             position = "identity"), 
               g$layers)

Here, g is ggdotchart part of your code without geom_errorbar.