rplotly

How to make plotly axes display only integer numbers


I have a plotly barplot in a shiny app, showing factor levels on X axis. But on some number of inputs (2,3,4) it shows marks like 1.5, 2.5 etc (see an image). So there is a question: can I somehow make the X axis marks show only integer values?

sample


Solution

  • plotly is guessing your axis types since your cluster labels are numeric. You can fix this by coercing your x var to a factor before/when plotting.

    library(plotly)
    library(dplyr)
    mtcars_by_gear <- count(mtcars,gear)
    
    plot_ly(mtcars_by_gear,
            x=~as.factor(gear), 
            y=~n)
    

    If you want further control over axis labels you can use the layout() function's tick arguments, but the factor option seems better for your case.

    plot_ly(mtcars_by_gear,
            x=~gear, 
            y=~n, 
            type="bar") %>% 
      layout(xaxis=list(tickvals=~gear,ticktext=~gear))