I am trying to generate a histogram in rbokeh.
The direct approach ly_hist leads to an unexpected counts (fig below, top). The indirect approach ly_bar gives a x-axis that is not sorted by factor level (fig below, bottom).
rbokeh

ggplot2 gives the expected results.

code:
library(data.table)
library(rbokeh)
library(ggplot2)
# generate data ==============
set.seed(123)
x = data.table(
hour = sample.int(n = 24, size = 100, replace = T)
)
# summarize
y = x[, .N, keyby = hour]
# ggplot ======================
theme_set(theme_bw())
g1 = ggplot(x) +
geom_histogram(aes(hour), bins = 24, fill = "steelblue", col = "white", alpha = 0.5 ) +
scale_x_continuous(breaks = seq(1, 24, 1))
g2 = ggplot(y) +
geom_bar(aes(hour, N), stat = "identity", fill = "steelblue", alpha = 0.5)
# rbokeh ==================
b1 = figure() %>%
ly_hist(hour, data = x, breaks = 24)
y[, hour := factor(hour)]
b2 = figure() %>%
ly_bar(hour, N, data = y)
Q: (1) how can I generate a histogram using rbokeh that produces the expected result (as in ggplot2) and (2) how can I get the x-axis to be sorted in the right order?
The ly_hist function treats the data as continuous and therefore bins it, so the output obtained for ly_hist should be expected.
For ly_bar, you can control the x axis by either specifying the xlim argument to figure():
figure(xlim = as.character(1:24)) %>%
ly_bar(hour, N, data = y)
or by piping the figure through the x_range() function:
figure() %>%
ly_bar(hour, N, data = y) %>%
x_range(as.character(1:24))
Also note that if you do not want to do the summarization up front, you can just pass the x variable and it will count things up.
figure(xlim = as.character(1:24)) %>%
ly_bar(as.character(hour), data = x)
By default, ideally rbokeh should honor factor level ordering for axes and should be able to handle inputs of unexpected types more gracefully (to avoid the as.character() business), and these will be addressed in future updates.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With