rggplot2viridis

getting discreet variables to always plot in the same color with viridis and ggplot


I am making multiple plots, that contain the same 4 discrete values, unknown, Negative, Neutral, Positive.

However not all of the data sets contain all the discrete values, and as such

in plot 1, unknown = yellow

in plot 2, unknown = purple, etc...

How can I set it so that, unknown allways = yellow, negative = purple...

below is the code i am using

library(viridis)
p <- ggplot() +
  geom_polygon(data = spdfMelbSent_fortified2.1, aes(fill = sentiment, x = long, y = lat, group = group) , size= 0, alpha=1) +
  theme_void() +
  scale_fill_viridis(discrete = TRUE, breaks=c('unknown','Negative','Neutral','Positive'), name="sentiment", guide =   guide_legend( keyheight = unit(3, units = "mm"), keywidth=unit(12, units = "mm"), label.position = "bottom",       title.position = 'top', nrow=1) ) +
  labs(
    title = "Melbourne and Geelong",
    subtitle = "Sentiment 27th April" 

  ) +
  theme(
    text = element_text(color = "#22211d"), 
    plot.background = element_rect(fill = "#f5f5f2", color = NA), 
    panel.background = element_rect(fill = "#f5f5f2", color = NA), 
    legend.background = element_rect(fill = "#f5f5f2", color = NA),

    plot.title = element_text(size= 22, hjust=0.01, color = "#4e4d47", margin = margin(b = -0.1, t = 0.4, l = 2, unit = "cm")),
    plot.subtitle = element_text(size= 17, hjust=0.01, color = "#4e4d47", margin = margin(b = -0.1, t = 0.43, l = 2, unit = "cm")),
    plot.caption = element_text( size=12, color = "#4e4d47", margin = margin(b = 0.3, r=-99, unit = "cm") ),

    legend.position = c(0.7, 0.09)
  ) +
  coord_map()
p 

Solution

  • I'm just copying my comment as an answer to mark this question as answered.

    It seems like you are missing a limits in your fill scale, which defines possible values and their order.

    Adding limits = c("unknown", "Negative", "Neutral", "Positive") inside the scale_fill_viridis() call could solve the inconsistencies across multiple plots where one or more levels have been dropped.