Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

r - ggplot2: show missing value colour in legend

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 
it 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 
it eat?", 
            breaks=c("herbi", "carni", "omni", "insecti", "unknown"), 
                labels=c("plants", "meat", "both", "insects", "don't know"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...