Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make a histogram in rbokeh?

Tags:

r

ggplot2

rbokeh

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

enter image description here

ggplot2 gives the expected results.

enter image description here

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?

like image 827
Henk Avatar asked Dec 06 '25 08:12

Henk


1 Answers

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.

like image 185
Ryan Avatar answered Dec 08 '25 20:12

Ryan



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!