Remove unused factor levels from a ggplot bar plot

前端 未结 2 1550
孤街浪徒
孤街浪徒 2020-12-03 07:20

I want to do the opposite of this question, and sort of the opposite of this question, though that\'s about legends, not the plot itself.

The other SO questions seem

相关标签:
2条回答
  • 2020-12-03 07:56

    Notice that, when plotting, you're using only two columns of your data frame, meaning that, rather than passing your whole data.frame you could take the relevant columns x[,c("name", "var1")] apply na.omit to remove the unwanted rows (as Gavin Simpson suggests) na.omit(x[,c("name", "var1")]) and then plot this data.

    My R/ggplot is quite rusty, and I realise that there are probably cleaner ways to achieve this.

    0 讨论(0)
  • 2020-12-03 08:22

    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()
    
    0 讨论(0)
提交回复
热议问题