How to remove empty factors from xaxis

Viewed 478

Trying to make interactive plotly barchart with filter_select() and no-shiny work. I am working with data for a lot of airports (> 100). A barchart is typically too crowded to support the user to compare the performance observed (value VAL) at one airport (APT_x) to a subset of peers. The idea is to use a filter to have the user select the subset of airports.

# create a dummy table with data for year, airport, and oberved value
yr <- c(2017, 2018, 2019)
ap <- c("APT_1", "APT_2", "APT_3", "APT_N")

df <- expand.grid(YEAR = yr, APT = ap)
df$VAL <- c(10, 11, 12, 14, 9, 8, 7, 6, 2, 10, 12, 13)

library(plotly)
# shared data
df_sh <- highlight_key(df, key=~APT)

# filters
ap_filter <- filter_select(id="airport",label="filter airport", sharedData=df_sh, group=~APT)

# stacked bar chart
bc <- df_sh %>% plot_ly(x=~APT, y=~VAL, color=~factor(YEAR)) %>%
  group_by(APT) %>%
  add_bars() %>%
  layout(barmode = "stack")

# arrange plot
bscols(widths = c(3, 9)
       , ap_filter
       , bc
       )

Whenever more than one airport APT is selected, the x-axis shows all the entity-ticks between the bars. How can this be removed/surpressed? Obviously, in the following example, APT_2 should not be shown. Thanks for any pointers. enter image description here

1 Answers

I got an answer to the same issue here. All that is needed is to set categoryorder = "trace" in the layout of the axis you are interested in. In your example, it is (only difference is in the layout call of the bc definition):

library(crosstalk) 
library(plotly)  

# create a dummy table with data for year, airport, and oberved value
yr <- c(2017, 2018, 2019)
ap <- c("APT_1", "APT_2", "APT_3", "APT_N")
df <- expand.grid(YEAR = yr, APT = ap)
df$VAL <- c(10, 11, 12, 14, 9, 8, 7, 6, 2, 10, 12, 13)

# shared data
df_sh <- highlight_key(df, key = ~APT)

# filters
ap_filter <- filter_select(id = "airport", label = "filter airport", sharedData = df_sh, group = ~APT)

# stacked bar chart
bc <- df_sh %>% plot_ly(x = ~APT, y = ~VAL, color = ~factor(YEAR)) %>%
  group_by(APT) %>%
  add_bars() %>%
  layout(barmode = "stack", 
         xaxis = list(categoryorder = "trace"))

# arrange plot
bscols(widths = c(3, 9), ap_filter, bc)
Related