Search code examples
rggplot2ggvis

Log-scale histogram with formatted breaks in ggvis


I'm interested in converting some graphs from ggplot to ggvis, but there is relatively little information on some of ggvis the functionality.

I have a graph of bit rates that I need plotted in log scale with nicely formatted labels.

Here's the code to do it in ggplot:

require(data.table)  # data.table_1.9.2
require(magrittr)    # magrittr_1.0.1
require(ggplot2)     # ggplot2_1.0.0
require(ggvis)       # ggvis_0.3.0.99

# Management requires nice labels on their graphs
format_si = function(unit="", ...) {
  # Returns a function that formats its input in SI-style (poswers of ten)
  # The function inserts the supplied unit
  function(x) {
    limits <- c(1e-24, 1e-21, 1e-18, 1e-15, 1e-12, 1e-9,  1e-6,  1e-3,  1e0,  1e3,  1e6,  1e9,  1e12,  1e15,  1e18, 1e21,  1e24)
    prefix <- c(" y",  " z",  " a",  " f",  " p",  " n",  " µ",  " m",  " ",  " k", " M", " G", " T",  " P",  " E", " Z",  " Y")
    i <- findInterval(abs(x), limits)
    i <- ifelse(i==0, which(limits == 1e0), i)
    paste(format(round(x/limits[i], 1), trim=TRUE, scientific=FALSE, ...), prefix[i], unit, sep="")
  }   
}   

# Create some sample data.
data = data.table(bitrate=rgamma(200, shape = 1.5, scale = 5e6))

# Make a wonderful ggplot2 bitmap graph.
data %>%
    ggplot(aes(bitrate)) +
    geom_bar(stat="bin", binwidth=.5, aes(y=..density..), fill="#ccccff", color="black") +
    scale_x_log10(breaks=10^(4:9), labels=format_si('bit/s')(10^(4:9)), limits=c(10^4,10^9))

ggplot bitrate

Trying to create the basic ggvis plot works:

# Create a non-log ggvis super awesome web graph.
data.table(bitrate=rgamma(200, shape = 1.5, scale = 5e6)) %>%
    ggvis(x = ~bitrate) %>%
    compute_bin(~bitrate) %>%
    layer_rects(x = ~xmin_, x2 = ~xmax_, y=~count_, y2=0) 

But if we simply add a log scale then boom, now the graph is blank:

# Try to add a log scale.
data.table(bitrate=rgamma(200, shape = 1.5, scale = 5e6)) %>%
    ggvis(x = ~bitrate) %>%
    compute_bin(~bitrate) %>%
    layer_rects(x = ~xmin_, x2 = ~xmax_, y=~count_, y2=0) %>%
    scale_numeric("x", trans="log") 

Is it possible to recreate the ggplot graph in ggvis? What about adding labelled breaks, or a label formatting function to ggvis axes?


Solution

  • Try adding expand = 0:

    scale_numeric("x", trans = "log", expand = 0)