MatthewBJane / ThemePark

Fun ggplot themes for popular culture
http://matthewbjane.com/ThemePark/
MIT License
196 stars 13 forks source link

Need to use as.character for scale_color_manual #35

Closed jebyrnes closed 8 months ago

jebyrnes commented 12 months ago

I've run into a funny problem where the color vectors don't work in combination with scale_color_manual() and its values argument, unless you again as.character() them. Below are three plots with palmerpenguins. The middle, however, has grey colors, when it should not. What's going on here? The class of the color vector is character, so.....

#libraries
library(ggplot2)
library(ThemePark)
library(palmerpenguins)

# Base of the plot
pen_plot_base <- ggplot(data = penguins,
                        mapping = aes(x = body_mass_g,
                                      y = species,
                                      color = species))

# Works
pen_plot_base +
  geom_jitter(position = position_jitter(height = 0.1),
              alpha = 0.7) +
  scale_color_manual(values = c("#a62675ff", "#fdf6faff", "#d74ea2ff"))
#> Warning: Removed 2 rows containing missing values (`geom_point()`).


# Gray
pen_plot_base +
  geom_jitter(position = position_jitter(height = 0.1),
              alpha = 0.7) +
  scale_color_manual(values = barbie_theme_colors[1:3])
#> Warning: Removed 2 rows containing missing values (`geom_point()`).


# Works
pen_plot_base +
  geom_jitter(position = position_jitter(height = 0.1),
              alpha = 0.7) +
  scale_color_manual(values = as.character(barbie_theme_colors[1:3]))
#> Warning: Removed 2 rows containing missing values (`geom_point()`).

Created on 2023-09-15 with reprex v2.0.2

lcpilling commented 12 months ago

Seems to be because we assign names to the values in barbie_theme_colors so they can be referenced like barbie_theme_colors["text"]

See what happens here:

image

How to get around this, I do not know!

christopherkenny commented 12 months ago

Yeah, this is a function of ggplot2's design, which allows you to use the names within scale_manual to indicate the colors for each. Easiest thing is to just use unname() around it first. Best practice is normally to create a vector that has the names from your data as the names of the colors in the vector.