在ggplot geom_bar中更改NA值的标签和颜色?

时间:2017-06-27 08:29:14

标签: r ggplot2 legend na geom-bar

我有一个这样的情节:

data <- data.frame(time = c("time1", "time2", "time1"),
                   sex = c("m", "f", NA))

ggplot(data = data) +
  geom_bar(aes(x = time, y = (..count..)/sum(..count..),
               fill = sex),
           position = "fill") +
  scale_y_continuous(name = "percentation",
                     labels = scales::percent)

我正在尝试更改NA值的标签和颜色。我使用scale_fill_manual添加

  scale_fill_manual(labels = c("m" = "male",
                               "f" = "female",
                               "NA" = "unknown"),
                    values = c("m" = "blue",
                               "f" = "red",
                               "NA" = "green"))

不幸的是,这不起作用,所以我想问一下,如果有人可以帮我解决这个问题吗?是否有一个特殊的词或什么来选择NA值?另外,我希望保留直接分配,例如"m" = "male",而不只是写"male"来控制分配。

1 个答案:

答案 0 :(得分:0)

以下内容对我有用:

data <- data.frame(time = c("time1", "time2", "time1"),
                   sex = c("m", "f", NA))
data$sex = as.character(data$sex)

data$sex[is.na(data$sex)] <- "Unknown"


ggplot(data = data) +
  geom_bar(aes(x = time, y = (..count..)/sum(..count..),
               fill = sex),
           position = "fill") +
  scale_y_continuous(name = "percentation",
                     labels = scales::percent)

enter image description here

我不确定你是否可以直接这样做。因此,首先将NA转换为某些内容,然后您可以添加代码:

  scale_fill_manual(labels = c("m" = "male",
                               "f" = "female",
                               "Unknown" = "unknown"),
                    values = c("m" = "blue",
                               "f" = "red",
                               "Unknown" = "green"))