1
votes

I didn't find any information if multiple level x axis are available for plotly. I guess it is possible to do it in ggplot2 (eg. this SO thread) and then transform it with ggplotly() but I would prefer a plotly solution. Is this possible? At the moment I am using an auxiliary column which concatenates year and month to the format "2017-12".

Example dataset:

data.frame(
        year = c(2017, 2018, 2018, 2017, 2018, 2018),
       month = c(12, 1, 2, 12, 1, 2),
       value = c(120, 110, 130, 90, 100, 110)
)

The result should look like this (year and month on the x axis):

enter image description here

1
I'm not too familiar with plotly, so I can't try an answer here; but, have you tried making a new variable with a line break in it?, e.g., dataframe$label <- paste(dataframe$month, "\n", dataframe$year) and using that for the label? - Nova

1 Answers

4
votes

Since your x-axis values are just new line separated values you could paste the two columns and separate them with a HTML line break <br />. The labels are assigned to x-xaxis ticks.

library('plotly')

df <- data.frame(
  year = c(2017, 2018, 2018, 2017, 2018, 2018),
  month = c(12, 1, 2, 12, 1, 2),
  value = c(120, 110, 130, 90, 100, 110)
)

xaxis <- list('tickvals'= seq(1, length(df$year)),
              'ticktext' = paste(df$month, df$year, sep='<br />'),
              'tickmode' = 'array')

plot_ly(y=df$value, x=seq(1, length(df$year)), mode='lines', type='scatter') %>% layout(xaxis = xaxis)

enter image description here