[英]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:無法顯示完整的分類 x 軸
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.