How to Remove Na from a Factor Variable (And from a Ggplot Chart)

How to remove NA from a factor variable (and from a ggplot chart)?

assuming your data is in a data frame called dat

newdat <- dat[!is.na(dat$Factor), ]

not sure how to solve the problem inside of ggplot code

ggplot: remove NA factor level in legend

You have one data point where delay_class is NA, but tot_delay isn't. This point is not being caught by your filter. Changing your code to:

filter(flights, !is.na(delay_class)) %>% 
ggplot() +
geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill")

does the trick:

Sample Image

Alternatively, if you absolutely must have that extra point, you can override the fill legend as follows:

filter(flights, !is.na(tot_delay)) %>% 
ggplot() +
geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill") +
scale_fill_manual( breaks = c("none","short","medium","long"),
values = scales::hue_pal()(4) )

UPDATE: As pointed out in @gatsky's answer, all discrete scales also include the na.translate argument. The feature actually existed since ggplot 2.2.0; I just wasn't aware of it at the time I posted my answer. For completeness, its usage in the original question would look like

filter(flights, !is.na(tot_delay)) %>% 
ggplot() +
geom_bar(mapping = aes(x = carrier, fill = delay_class), position = "fill") +
scale_fill_discrete(na.translate=FALSE)

Remove unused factor levels from a ggplot bar plot

One easy options is to use na.omit() on your data frame df to remove those rows with NA

ggplot(na.omit(df), aes(x=name,y=var1)) + geom_bar()

Given your update, the following

ggplot(df[!is.na(df$var1), ], aes(x=name,y=var1)) + geom_bar()

works OK and only considers NA in Var1. Given that you are only plotting name and Var, apply na.omit() to a data frame containing only those variables

ggplot(na.omit(df[, c("name", "var1")]), aes(x=name,y=var1)) + geom_bar()

ggplot: how to remove unused factor levels from a facet?

Setting scales = free in facet grid will do the trick:

facet_grid( ~ fac, scales = "free")



Related Topics



Leave a reply



Submit