18

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

4 Answers 4

15

tickformat=',d'

Supposing the attributes are the same as in Python where I tested :-), you can set:

layout(xaxis=list(tickformat=',d'))

where the valid values are D3 formats.

See also: https://community.plot.ly/t/restrict-axis-ticks-labels-to-only-show-int-values/3503/4

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Congrats on 1k answers btw!
It seems it's more complicated to handle this appropriately. Using tickformat will frequently result in duplicate labels (i.e. both 1 and .75 entries will show as 1).
6

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))

Comments

3

If using python:

fig = px.bar(df, x='x', y='y', title="Count")
fig.update_layout( xaxis={
    'range': [df['x'].min(), df['x'].max()], 
    'tickvals': [*range(int(df['x'].min()), int(df['x'].max()))]
})
fig.show()

Also you can force the axis to be categorical:

fig = px.bar(df, x='x', y='y', title="Count")
fig.update_xaxes(type='category')
fig.show()

1 Comment

in your code tickvals won't include max value. Add +1 to the max inside the range.
0

waithira’s answer can be translated to R as follows:

plot_ly(df, x = ~x, y = ~y) |>
  layout(tickvals = c(0L, seq_len(max(df$x))))

If you don’t want to include 0 in the x-axis, remove c(0L, …) from around the seq_len() call.

You can also specify range = range(df$x) as shown in the other answer, but this should be strictly redundant since you are specifying ticks along the full range of the data.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.