简体   繁体   中英

R ggplot omit NA

I'm trying to do ggplots in R. My dataset has a few rows with NA for one or more variables. How do I get the NA not to show up on the graph? Here's my code:

met$marker_Degree2 = factor(met$marker_Degree, levels=c("none", "weak"))
p4 <- ggplot(met, aes(factor(marker_Degree2), avgtsh))
p4 + ggtitle('Serum marker and Tumor marker') +
geom_point(shape=21, size=4, aes(color=factor(marker_Degree2))) +
scale_color_manual(values = c("orange", "green")) +
theme_bw() +
xlab("Marker Tissue Staining Degree") +
ylab("Mean marker Level in Serum")

Here's an example

mydata <- data.frame(income=c(50000,NA,10000,30000), y=c("male", "female", NA, "female"))
p <- ggplot(mydata, aes(x,z))
p + geom_point()

Note that NA for numeric() data are hidden automatically, but not for character() data, so the NA shows up. So you need to do something like this.

plot_row <- apply(mydata, 1, function(x) sum(!is.na(x))) == ncol(mydata)
p <- ggplot(mydata[plot_row,], aes(x,z))
p + geom_point()

One way to handle the example you provided is as follows:

mydata <- data.frame(income=c(50000,NA,10000,30000), y=c("male", "female", NA, "female"))
p <- ggplot(mydata, aes(income,y))
p + geom_point(na.rm = TRUE) + ylim(labels=c("male", "female"))

Alternatively,

use:

ggplot(na.omit(mydata), aes(income,y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM