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?
4 Answers
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
2 Comments
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
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
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.
