Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set X Axis Range on Plotly Frequency Graph

Consider the following graph:

library(dplyr)
library(plotly)

x <- c(1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 8, 8, 8, 10, 10)
y <- as.data.frame(table(x))

y %>%
plot_ly(x = ~ x,
        y = ~ Freq,
        type = 'bar')

Frequency Graph

I would like to take this graph and produce a similar graph in which the values 7 and 9 are listed with a frequency of zero. Is there a way to get a frequency count of a sequence like seq(0, 10, 1) where 7 and 9 would appear as a frequency of 0 or is there a way that I can set the x axis on my plotly graph to be from 0 to 10 even though I don't have all the numbers in my data?

I have tried

y %>%
plot_ly(x = ~ x,
        y = ~ Freq,
        type = 'bar') %>%
layout(xaxis = list(autotick = FALSE, tick0 = 0, tickd = seq(0, 10, 1))

and also

layout(xaxis = list(autotick = FALSE, tick0 = 0, tickd = c(0,10))

but neither one seems to change anything.

I would like my desired output to look like this:

Desired Output

Note that This is just a small sample and my actual data will be much larger. Because of this, something like looping through the data and counting every number would be too slow.

like image 827
Dustin Knight Avatar asked Sep 12 '26 15:09

Dustin Knight


1 Answers

A simple solution is to convert x as a factor with levels from 1 to 10.

library(dplyr)
library(plotly)

x <- c(1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 6, 8, 8, 8, 10, 10)
x <- factor(x, levels=1:10)

y <- as.data.frame(table(x))

y %>%
plot_ly(x = ~ x,
        y = ~ Freq,
        type = 'bar')
like image 112
Marco Sandri Avatar answered Sep 15 '26 06:09

Marco Sandri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!