【问题标题】:getting discreet variables to always plot in the same color with viridis and ggplot使用 viridis 和 ggplot 使谨慎的变量始终以相同的颜色绘制
【发布时间】:2019-04-28 07:46:55
【问题描述】:

我正在制作多个图,其中包含相同的 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 

【问题讨论】:

  • 没有任何数据可玩,我们只能猜测。您能否尝试在您的 scale_fill_viridis() 通话中添加 limits = c("unknown", "Negative", "Neutral", "Positive) 看看是否有帮助?
  • @teunbrand,效果很好,如果你提交它作为答案,我会接受它

标签: r ggplot2 viridis


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-11-27
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-29
    • 2020-07-10
    相关资源
    最近更新 更多