ggplot2:在图例中显示缺失的颜色 [英] ggplot2: show missing value colour in legend

查看:794
本文介绍了ggplot2:在图例中显示缺失的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

只是想知道什么是需要的,所以缺失值的颜色显示在图例中?
从UseR看一个例子! ggplot2 book,p94

  p < -  qplot(sleep_total,sleep_cycle,data = msleep,color = vore)
p + scale_colour_hue(na.value =Black)
p + scale_colour_hue(What does \\\
it eat?,na.value =Black,breaks = c(herbi,carni,omni ,insecti,NA),标签= c(植物,肉,两者,昆虫,不知道))
pre>

vore = NA的数据点显示在图中,但NA未列在图例中。



感谢

解决方案

解决此问题的方法是将 NA 您的数据中的值与其他字符相同(例如,未知)和绘图数据。

具有 vore 值的变量vore2作为字符。然后将 NA 值替换为未知



<$ p $ msleep $ vore2< -as.character(msleep $ vore)
msleep $ vore2 [is.na(msleep $ vore2)]< - 未知

在绘图中,颜色使用了新变量 vore2

  p <-qplot(sleep_total,sleep_cycle,data = msleep,color = vore2)
p + scale_colour_hue( \\ nb eat?,
break = c(herbi,carni,omni,insecti,unknown),
labels = c(plants,meat ,Both,insects,do not know))


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

解决方案

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"))

这篇关于ggplot2:在图例中显示缺失的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆