首页 > 解决方案 > 即使没有要绘制的点,也显示完整的分类 x 轴

问题描述

我正在使用 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:无法显示完整的分类 x 轴
https://community.plot.ly/t/cannot-re -arrange-x-axis-when-axis-type-is-category/1274/3

标签: rr-plotly

解决方案


作为一种解决方法,我建议使用带有字符刻度文本的数字刻度:

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

结果


推荐阅读