coldy
coldy

Reputation: 2195

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

I am using plotly to plot a scatter plot with line+markers. The problem is that I have a categorical x-axis and I want to fix it for full range static on all plots.

Below is the example code:

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

The plot seems okay, but I want to fix the range of x-axis to values of hour_bins.

I have already looked up some of the articles on the same, but it does not seem to work under my condition:
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

Upvotes: 2

Views: 1423

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33510

As a workaround I'd suggest using numeric ticks with character ticktext:

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

Result

Upvotes: 3

Related Questions