1

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

Felix Grossmann
  • 1,224
  • 1
  • 11
  • 30
  • 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 Aug 28 '18 at 13:33
  • This https://stackoverflow.com/questions/51955803/how-to-change-x-axis-layout-using-plotly-in-r/51964142#51964142 could help you. – MLavoie Aug 28 '18 at 16:39

1 Answers1

4

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

Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99
  • can you help there too? https://stackoverflow.com/questions/52443673/one-zeroline-for-two-y-axis-in-plotly - thank you for looking into it in advance :) – Felix Grossmann Sep 26 '18 at 08:51