即使没有要绘制的点,也显示完整的分类 x 轴

Showing full categorical x-axis even when there are no points to plot

我正在使用 plotly 绘制带有线+标记的散点图。问题是我有一个分类 x 轴,我想修复它以在所有地块上实现全范围静态。

示例代码如下:

import(plotly)
x_group <- c('[8-9]','[9-10]','[10-11]','[11-12]','[12-13]','[13-14]','[14-15]','[16-17]','[17-18]','[18-19]','[19-20]')
total <- c('22','17','27','8 ','16','4 ','17','12','15','2 ','22')

example_df <- as.data.frame(list(hour_bin_grp= x_group, total = total))

m <- list(
  l = 50,
  r = 50,
  b = 100,
  t = 100,
  pad = 4
)

hour_bins <- c("[0-7]","[7-8]","[8-9]","[9-10]","[10-11]", "[11-12]","[12-13]", "[13-14]", "[14-15]", "[15-16]","[16-17]", "[17-18]","[18-19]", "[19-20]", "[20-21]","[21-22]")
p <- plot_ly(example_df, x = ~hour_bin_grp, y = ~total, type = 'scatter', mode = 'markers+lines') %>% 
  layout(autosize = T, margin = m,
         xaxis = list(
           type='category',
           categoryorder= 'array',
           showgrid = TRUE,
           autorange = FALSE,
           showticklabels = TRUE,
           categoryarray= unique(hour_bins)
         ),
         yaxis = list(
           showgrid = TRUE,
           autorange = TRUE,
           showline = TRUE,
           showticklabels = TRUE,
           rangemode = "tozero",
         ))
p

情节似乎还可以,但我想将 x 轴的范围固定为 hour_bins 的值。

我已经查阅了一些相同的文章,但在我的情况下似乎不起作用:
Plotly.js: Cannot show full categorical x-axis
https://community.plot.ly/t/cannot-re-arrange-x-axis-when-axis-type-is-category/1274/3

作为解决方法,我建议使用带有字符标记文本的数字标记:

library(plotly)

bin_df <- data.frame(hour_bins = c("[0-7]","[7-8]","[8-9]","[9-10]","[10-11]", "[11-12]","[12-13]", "[13-14]", "[14-15]", "[15-16]","[16-17]", "[17-18]","[18-19]", "[19-20]", "[20-21]","[21-22]"))
bin_df$hour_bin_grp <- seq_len(nrow(bin_df))

example_df <- data.frame(hour_bin_grp = bin_df$hour_bin_grp[bin_df$hour_bins %in% c('[8-9]','[9-10]','[10-11]','[11-12]','[12-13]','[13-14]','[14-15]','[16-17]','[17-18]','[18-19]','[19-20]')], total = as.numeric(c('22','17','27','8','16','4','17','12','15','2','22')))

p <- plot_ly(example_df, x = ~hour_bin_grp, y = ~total, type = 'scatter', mode = 'markers+lines') %>% 
  layout(xaxis = list(
    tickmode = "array",
    tickvals = bin_df$hour_bin_grp,
    ticktext = example_df$hour_bins,
    range = list(min(bin_df$hour_bin_grp), max(bin_df$hour_bin_grp))
  ))
p