Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: update fct_reorder to support horizontal bar plots with NA bars on the bottom #266

Open
davidhodge931 opened this issue Jul 8, 2020 · 1 comment
Labels
feature a feature request or enhancement

Comments

@davidhodge931
Copy link

@davidhodge931 davidhodge931 commented Jul 8, 2020

It is not currently possible to easily make a horizontal bar graph where bars are ordered by size and with NA bars on the bottom of the graph.

The graph looks good vertically with NAs on the far right, but as soon as you flip the plot, the NAs are at the top, which in general is not good, given that you almost never want to emphasise the NA values.

A solution to this might be to update forcats::fct_reorder to have an argument to support this (e.g. na_flip = TRUE).

library(dplyr)
library(ggplot2)

plot_data <- iris %>% 
  group_by(Species) %>% 
  summarise(Petal.Length = mean(Petal.Length)) %>% 
  add_row(Species = "New species") %>% 
  mutate(Species = forcats::fct_reorder(Species, Petal.Length))

ggplot(plot_data) +
  geom_col(aes(Species, Petal.Length))

image

ggplot(plot_data) +
  geom_col(aes(Species, Petal.Length)) + 
  coord_flip()

image

@davidhodge931 davidhodge931 changed the title New feature: update fct_reorder to support horizontal bar plots with NA bars on the bottom Feature request: update fct_reorder to support horizontal bar plots with NA bars on the bottom Jul 8, 2020
@davidhodge931
Copy link
Author

@davidhodge931 davidhodge931 commented Sep 29, 2020

A workaround...

library(dplyr)
library(ggplot2)

df <- tibble::tribble(
  ~region, ~year, ~data_value,
  "A", "2012", 3423,
  "A", "2017", 4423,
  "B", "2012", NA,
  "B", "2017", 2423,
  "C", "2012", NA,
  "C", "2017", NA)

all_na <- df %>% 
  group_by(region) %>% #if colouring
  summarise(all_na = all(is.na(data_value))) %>% 
  filter(all_na == TRUE) %>% 
  pull(region)

df <- df %>% 
  mutate(region = forcats::fct_reorder(region, data_value, .fun = median, na.rm = TRUE))  

levels(df$region)

ggplot(df) +
  geom_col(aes(x = region, y = data_value, fill = year), position = "dodge") +
  coord_flip()

df <- df %>% 
  mutate(region = forcats::fct_relevel(region, all_na))  

levels(df$region)

ggplot(df) +
  geom_col(aes(x = region, y = data_value, fill = year), position = "dodge") +
  coord_flip()

@hadley hadley added the feature a feature request or enhancement label Dec 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature a feature request or enhancement
Projects
None yet
Development

No branches or pull requests

2 participants