如何从 xaxis 中删除空因子

Ray*_*Ray 5 r filter plotly

尝试使用 filter_select() 和无光泽的工作制作交互式绘图条形图。我正在处理许多机场(> 100)的数据。条形图通常过于拥挤,无法支持用户将在一个机场 (APT_x) 上观察到的性能(值 VAL)与同级的子集进行比较。这个想法是使用过滤器让用户选择机场的子集。

# 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
       )
Run Code Online (Sandbox Code Playgroud)

Whenever more than one airport APT is selected, the x-axis shows all the entity-ticks between the bars. 如何删除/抑制它?显然,在以下示例中,不应显示 APT_2。感谢您的指点。 在此处输入图片说明

dgd*_*gdi 1

我在这里得到了同一问题的答案。所需要做的就是在您感兴趣的轴的布局中设置categoryorder =“trace”。在您的示例中,它是(唯一的区别在于 bc 定义的布局调用):

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)
Run Code Online (Sandbox Code Playgroud)