I have the simple dataframe d
below and I want to create a histogram based on the frequency of its values. I am trying to set the inital value as 0
and then display the values in the x-axis by 5
but neither of those seems to work since values begin from 1
and then display 8
. I found out that this happens because my dataframe does not have 2
and 3
as values so the counting stops at 1
and begings from 4
until 8
because my dataframe includes 4,5,6,7,8
as values so the counting stops normally.
The solutions might be 2. The first one to find a way to display values with zero frequency on the axis and the second to set the correct tick formating without those values on the axis.
I would prefer a clear plotly solution on this as first choice, without ggplot()
interference.
d<-data.frame(c(1,5,7,5,4,5,6,7,8,9,10,15,13))
x <- list(
tick0=0,
dtick=5
)
# Create the plotly histogram
plot_ly(alpha = 0.9) %>%
add_histogram(x = as.factor(d[,1]),source="subset") %>%
# Add titles in plot and axes
layout(barmode = "overlay",xaxis=x,margin=list(b=100))
There is a trick, using categoryorder = "array"
and categoryarray = x_axis_values
in xaxis layout. With these you can manually set the values that xaxis will contain.
I had modified a little your example of code, but this should do the trick:
# yours data
d = c(1,5,7,5,4,5,6,7,8,9,10,15,13)
# Create the plotly histogram
plot_ly(alpha = 0.9) %>%
add_histogram(x = as.character(d)
) %>%
# Add titles in plot and axes
layout(barmode = "overlay",
margin=list(b=100),
# Set the xaxis values
xaxis=list(categoryorder="array",
categoryarray = as.character(min(d):max(d))
)
)
Here the output: