使用 viridis 和 ggplot 使谨慎的变量始终以相同的颜色绘制

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

我正在制作多个图,其中包含相同的 4 个离散值,未知、负、中性、正。

然而,并非所有数据集都包含所有离散值,因此

在情节 1 中,未知 = 黄色

在情节 2 中,未知 = 紫色, 等...

如何设置,未知总是=黄色,负=紫色...

下面是我使用的代码

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 

我只是复制我的评论作为答案以将此问题标记为已回答。

您的填充比例似乎缺少 limits,它定义了可能的值及其顺序。

scale_fill_viridis() 调用中添加 limits = c("unknown", "Negative", "Neutral", "Positive") 可以解决已删除一个或多个级别的多个地块之间的不一致。