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:
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
Creating a New Column Based on Unique Id With Values in R
How to Replace Negative Values in a Dataframe Column With a Different Value
R: How to Check If All Columns in a Data.Frame Are the Same
How to Join (Merge) Data Frames (Inner, Outer, Left, Right)
Finding All Duplicate Rows, Including "Elements With Smaller Subscripts"
Gather Multiple Sets of Columns
Ggplot'S Qplot Does Not Execute on Sourcing
Multirow Axis Labels With Nested Grouping Variables
Split String Column to Create New Binary Columns
Removing All Empty Columns and Rows in Data.Frame When Rows Don't Go Away
Create Counter Within Consecutive Runs of Values
How to Reshape Data from Long to Wide Format
Understanding Exactly When a Data.Table Is a Reference to (Vs a Copy Of) Another Data.Table
Convert Data from Long Format to Wide Format With Multiple Measure Columns
Replace Na With Previous or Next Value, by Group, Using Dplyr