scale_fill_manual define color for NA values

雨燕双飞 提交于 2019-12-19 00:17:50

问题


I try to make a barplot with ggplot2 and am facing some issues with defining the color for NA.

ggh <- ggplot(data=dat, aes(x=var1, fill=var2))+
  geom_bar(position="dodge")+
  scale_fill_manual(
    values=c("s"="steelblue", "i"="darkgoldenrod2", "r"="firebrick4", na.value="black"))

In my var2 I have values c("s", "i", "r", NA). For some reason my code above inside the scale_fill_manual does not work for NA, even if it works fine for all the others values.

Can someone help me figure out why?

Thanks for the help


回答1:


The na.value needs to be outside of the values argument. Here is an example:

library(ggplot2)

set.seed(42)

mydata <- data.frame(var1 = sample(c("A", "B", "C", "D"), 150, replace = TRUE),
                     var2 = sample(c("s", "i", "r", NA), 150, replace = TRUE))

ggplot(mydata) +
  aes(x = var1, fill = var2) +
  geom_bar() + 
  scale_fill_manual(values = c("s" = "steelblue",
                               "i" = "darkgoldenrod2",
                               "r" = "firebrick4"),
                    na.value = "black")



来源:https://stackoverflow.com/questions/45144630/scale-fill-manual-define-color-for-na-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!