ggplot2: show missing value colour in legend

萝らか妹 提交于 2019-11-26 22:05:18

问题


Just wondering what is required so the colour for missing values is shown in the legend? Looking at example from the UseR! ggplot2 book, p94

p <- qplot(sleep_total, sleep_cycle, data=msleep, colour=vore)
p + scale_colour_hue(na.value = "Black")
p +  scale_colour_hue("What does \nit eat?", na.value="Black", breaks=c("herbi", "carni", "omni", "insecti", NA), labels=c("plants", "meat", "both", "insects", "don't know"))

the data point for vore=NA is shown in the plot but NA is not listed in the legend.

Thanks


回答1:


Workaround for the problem would be to replace NA values in your data with same other character (for example, unknown) and plot data.

So, made new variable vore2 that has vore values as characters. Then replaced NA values with the unknown.

msleep$vore2<-as.character(msleep$vore)
msleep$vore2[is.na(msleep$vore2)]<-"unknown"

In the plot used new variable vore2 for the colors.

p <- qplot(sleep_total, sleep_cycle, data=msleep, colour=vore2)
p +  scale_colour_hue("What does \nit eat?", 
            breaks=c("herbi", "carni", "omni", "insecti", "unknown"), 
                labels=c("plants", "meat", "both", "insects", "don't know"))


来源:https://stackoverflow.com/questions/17848674/ggplot2-show-missing-value-colour-in-legend

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