NA's are being plotted in boxplot ggplot2

蓝咒 提交于 2019-12-05 12:05:50

问题


I'm trying to plot a v. simple boxplot in ggplot2. I have species richness vs. landuse class. However, I have 2 NA's in my data. For some strange reason, they're being plotted, even when they're being understood as NA's by R. Any suggestion to remove them?

The code I'm using is:

ggplot(data, aes(x=luse, y=rich))+
  geom_boxplot(mapping = NULL, data = NULL, stat = "boxplot", position = "dodge", outlier.colour = "red", outlier.shape = 16, outlier.size = 2, notch = F, notchwidth = 0.5)+
  scale_x_discrete("luse", drop=T)+
  geom_smooth(method="loess",aes(group=1))

However, the graph includes 2 NA's for luse. Unfortunately I cannot post images, but imagine that a NA bar is being added to my graph.


回答1:


You may try to use the subset() function in the first line of your code

ggplot(data=subset(data, !is.na(luse)), aes(x=luse, y=rich))+

as suggested in: Eliminating NAs from a ggplot




回答2:


You can also use the filter() function in dplyr/tidyverse:

data %>% filter(is.na(luse) == FALSE) %>% 
   ggplot(aes(x=luse, y=rich)) +
   geom_boxplot()

This way you don't have to create a new object.




回答3:


Here is a formal answer using the comments above to incorporate !is.na() with filter() from tidyverse/dplyr. If you have a basic tidyverse operation such as filtering NAs, you can do it right in the ggplot call, as suggested, to avoid making a new data frame:

ggplot(data %>% filter(!is.na(luse)), aes(x = luse, y = rich)) + geom_boxplot()



来源:https://stackoverflow.com/questions/17146213/nas-are-being-plotted-in-boxplot-ggplot2

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