1

I am having a strange issue where saving a ggplot figure that I make does not maintain the colors I set using scale_color_manual. I have made a reproducible example (with some editing) using the mtcars dataset.

    plot1 <- ggplot(data = mtcars %>% rownames_to_column("type") %>% 
                  dplyr::filter(between(cyl, 6, 8)) %>% 
                  dplyr::filter(between(gear, 4, 5))
) +
  aes(y = wt, x = type) +
  geom_boxplot(outlier.size = 0) +
  geom_jitter(aes(color = factor(cyl), shape = factor(gear)), size = 10, position=position_jitter(width=.25, height=0)) +
  #geom_smooth(method = lm, se = TRUE) +
  scale_shape_manual(values=c("",""), name = "Gear", labels = c("4", "5")) + # I need 9 values (I for each ID)
  scale_color_manual(values=c('red4', 'springgreen4'), name = "cyl", labels = c("4 cylinder", "5 cylinder"))  +
  # # geom_jitter(size=8, aes(shape=Sex, color=Sex), position = position_dodge(.4)) +
  theme(legend.position = "top",
        plot.title = element_text(hjust = 0.5) # Center the text title) 
  ) 

ggsave("images/review/mean_AllAgents_test.png",plot1, width=11, height=6.5, dpi=400)

The figure in the RStudio "Plots" pane has cyl colored in red and green shown below

img

Whereas the file saved using ggsave does not show these colors.

img

I have tried using the fix from this SO post. I also have tried using cowplot::save_plot. The colors do remain if I manually Export the figure from the "Plots" pane.

Does anyone know why this is occurring?

R version 4.0.4 (2021-02-15)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)

Matrix products: default

locale:
[1] LC_COLLATE=English_Canada.1252  LC_CTYPE=English_Canada.1252    LC_MONETARY=English_Canada.1252 LC_NUMERIC=C                   
[5] LC_TIME=English_Canada.1252    

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] apastats_0.3         ggstatsplot_0.8.0    rstatix_0.7.0        hrbrthemes_0.8.0     gtsummary_1.4.2.9011 car_3.0-11          
 [7] carData_3.0-4        forcats_0.5.1        stringr_1.4.0        dplyr_1.0.6          purrr_0.3.4          readr_2.0.0         
[13] tidyr_1.1.3          tibble_3.1.2         tidyverse_1.3.1      Rmisc_1.5            plyr_1.8.6           lattice_0.20-41     
[19] ggplot2_3.3.5        rio_0.5.27           pacman_0.5.1        

EDIT

I was asked to provide additional detail in my Preferences

img

Patrick
  • 915
  • 2
  • 9
  • 26

0 Answers0