Showing posts with label clickme. Show all posts
Showing posts with label clickme. Show all posts

Wednesday, April 17, 2013

Banging on the JGBs

Since I have not posted in quite a while, I wanted to let everyone know that I am still alive and kicking.  The resurrection of excitement (opportunity) in the markets, quarterly reporting cycle, and the overwhelming number of unbelievable R/javascript releases have kept me from writing something good enough to justify a post.   In the markets, Japan and gold bring a smile to my face.    Nothing particularly new on the quarterly reporting cycle, but I have been watching the interesting ideas at http://axysreporting.com closely, and I have enjoyed learning a little about http://addepar.com.  Nothing though impresses me as much as all of the R and javascript packages that have been announced over the last two weeks.  I mentioned them in my post d3 Lifeline from vega and clickme, but I forgot to include Introducing the healthvis R package – one line D3 graphics with R from Jeff Leek who taught https://www.coursera.org/course/dataanalysis, and rCharts was not yet released.  rCharts reminded me of the very special slidify package that I have to my own detriment not used until now.  I strongly, strongly recommend readers to thoroughly look at  rCharts  and slidify.  Just to make sure everyone sees all of these, I have relisted them and added new links below with the Twitter announcements.

vega

Announcing Vega, a new visualization grammar built on #d3js! Design reusable chart components in a JSON format trifacta.github.com/vega

— Jeffrey Heer (@jeffrey_heer) April 2, 2013

 

rCharts from the same creator as slidify

@lisaczhang I wrote an R package wrapping functionality of Polycharts for R users. ramnathv.github.io/rCharts

— Ramnath Vaidyanathan (@ramnath_vaidya) April 10, 2013

 

clickme

@xieyihui I'd love your feedback on clickme, an R package to populate JS visualizations using #knitr bitly.com/vizbi_clickme

— Nacho Caballero (@nachocaballero) March 24, 2013

 

rhealthvis

Our package is announced today! healthvis.org

— rhealthvis (@rhealthvis) April 2, 2013

Now to show some of the results from my experiments, I will list some bl.ocks below.  The primary data source for all of these has been the Japanese Government Bond (JGB) yield data provided by the Japanese Ministry of Finance.  I will discuss the reasons for choosing JGBs in a much more thorough later post.  I would love thoughts on JGBs and my experiments.

  1. http://bl.ocks.org/timelyportfolio/5407807  JGB Yields in Small Multiples with clickme ractive
  2. http://bl.ocks.org/timelyportfolio/5405240  JGB Yield Curve with a vega spec and clickme ractive
  3. http://bl.ocks.org/timelyportfolio/5398614  JGB Yields Line Chart with a vega spec and clickme ractive

Some of my other more basic experiments are here.  These might be helpful to anyone not yet familiar with these new resources.

  1. http://bl.ocks.org/timelyportfolio/5351448
  2. http://bl.ocks.org/timelyportfolio/5342818
  3. http://bl.ocks.org/timelyportfolio/5322390
  4. http://bl.ocks.org/timelyportfolio/5316682

 

I’ll be back soon with what I hope is a very impressive slidify created market-related post.  Until then, please let me know what you think, or show your relevant experiments.

 

Thanks to everyone that has worked so hard creating these great open source projects.

Thursday, April 4, 2013

d3 Lifeline from vega and clickme

This has been an exciting week for d3.js and R with the

  1. release of vega by the data vis powerhouses at Trifacta
  2. launch of clickme and already significant rewrite to accommodate vega
  3. inception of a very promising d3 templates DexCharts described in multiple posts.

I am glad to have had time to play with all three, and I have actually already used them for legitimate purposes. I only understand the basics, but I thought I would post how we can combine a clickme ractive and a vega template to produce the lifelines example included in vega. I like the lifelines example because it is the one with the most complex data source and number of d3 elements. Fortunately, both projects are well documented, especially for early releases. I strongly recommend reading through both wikis to quickly progress along the learning curve. I will try to fill in some gaps in the clickmeclickme and vega” wiki page.

vega frameworks

vega frameworks are JSON objects to ease the construction of interactive d3 visualizations. In the wiki, the authors liken vega to ggplot2 but say

However, in service of rapid specification these systems make a number of decisions on behalf of the user, and also impose limits on the type of visualizations one can create. vega is intended to be lower-level, enabling fine-gained control of the visualization design.

ggplot2 and lattice users should immediately be familiar with words like “axes”,“scales”, “data”, and “marks”.

clickme ractives

clickme ractives are a directory structure with files that provide at a minimum a R markdown template (template.rmd) for a visualization and a R translator (translator.r) to allow the use of R data and calculations in the finished HTML5 rendering. Although clickme was developed unaware of vega, the author immediately saw the potential of combining both and rewrote clickme to allow easy integration. The synergy of the two is demonstrated by the ability to create 7 vega examples with all the same template.rmd and translator.r. vega templates now fall in the spec subdirectory of the data directory of a clickme ractive.

clickme filling vega

If we look at the original lifelines vega spec, we will see some spots where we might like R to provide the information, such as

...
"width": 400,
"height": 100,
"padding": {"top": 60, "left": 5, "bottom": 30, "right": 30},
"data": [
{
"name": "people",
"values": [
{"label":"Washington", "born":-7506057600000, "died":-5365324800000,
"enter":-5701424400000, "leave":-5453884800000},
...
"name": "events",
"format": {"type":"json", "parse":{"when":"date"}},
"values": [
{"name":"Decl. of Independence", "when":"July 4, 1776"},

I am guessing that some R users might stumble a little with the data section of this JSON, so let's translate into lists, something I hope might be a little more familiar.

data = list(
list(name="people",
values=list(
list(label="Washington", born=-7506057600000, died=-5365324800000, enter=-5701424400000, leave=-5453884800000),
list(label="Adams", born=-7389766800000, died=-4528285200000, enter=-5453884800000, leave=-5327740800000),
list(label="Jefferson", born=-7154586000000, died=-4528285200000, enter=-5327740800000, leave=-5075280000000),
list(label="Madison", born=-6904544400000, died=-4213184400000, enter=-5075280000000, leave=-4822819200000),
list(label="Monroe", born=-6679904400000, died=-4370518800000, enter=-4822819200000, leave=-4570358400000)
)
),
list(
name= "events",
format= list(type="json", parse=list(when="date")),
values= list(
list(name="Decl. of Independence", when="July 4, 1776"),
list(name="U.S. Constitution", when="3/4/1789"),
list(name="Louisiana Purchase", when="April 30, 1803"),
list(name="Monroe Doctrine", when="Dec 2, 1823")
)

)
)

Then in the translator.R part of our ractive, we can use the rjson package to translate the list into a JSON equivalent. Most of the data for d3 and vega can usually  just come from data.frames. The clickme author actually also wrote df2json to better handle the translation of data.frames to JSON, and there are numerous ractive examples using data.frames in the clickme package.

  get_data_as_json <- function(opts) {
...
} else {
library(rjson)
json_data <- toJSON(opts$data) ##opts$data comes from the data parameter of the clickme function
}
json_data
}

Now we just need to fill the vega spec with our data. We can replace the data section with

"data": {{ get_data_as_json(opts) }}

When we run the clickme_vega function, clickme will use the knit_expand function from knitr to expand/run the get_data_as_json function on the data supplied as a parameter to clickme_vega and replace like a mail merge with our translated JSON data representation.  With our ractive, we will also specify height, width, margins, title, etc. We can produce our HTML page with just one line.

clickme_vega(data,"lifelines",params=list(height=100,width=400,padding=list(top=60, left=5, bottom= 30, right=30)))

R to clickme to vega to d3 visualization workflow


Assuming we already have a predefined clickme ractive and vega spec, the workflow from R to a pretty d3 visualization becomes ridiculously easy:



  1. Just like we would if we were creating an R graph, we get our data, clean our data, and run our calculations
  2. in R, we run clickme_vega(data=our_data_from_step1, ractive=nameofourractive)
  3. show off and use our amazing, beautiful, and interactive visualization (might need a simple http server for some cases).

If we do not have a predefined clickme ractive, then we can easily borrow/steal from the unbelievable repository of d3 examples or a possible future vega repository, and follow the instructions in the clickme wiki to convert into a ractive.


Live Example


if embed does not show go to http://bl.ocks.org/timelyportfolio/5316682.


Reproduce me


Below is all the code to run this specific example. The ractive and vega spec are in this Git repo.

#if not already installed, uncomment the two lines below
#library(devtools)
#install_github("clickme", "nachocab")

require(clickme)
#set location where you put your multiline ractive
set_root_path("path to your ractive/r")

data = list(
list(name="people",
values=list(
list(label="Washington", born=-7506057600000, died=-5365324800000, enter=-5701424400000, leave=-5453884800000),
list(label="Adams", born=-7389766800000, died=-4528285200000, enter=-5453884800000, leave=-5327740800000),
list(label="Jefferson", born=-7154586000000, died=-4528285200000, enter=-5327740800000, leave=-5075280000000),
list(label="Madison", born=-6904544400000, died=-4213184400000, enter=-5075280000000, leave=-4822819200000),
list(label="Monroe", born=-6679904400000, died=-4370518800000, enter=-4822819200000, leave=-4570358400000)
)
),
list(
name= "events",
format= list(type="json", parse=list(when="date")),
values= list(
list(name="Decl. of Independence", when="July 4, 1776"),
list(name="U.S. Constitution", when="3/4/1789"),
list(name="Louisiana Purchase", when="April 30, 1803"),
list(name="Monroe Doctrine", when="Dec 2, 1823")
)

)
)

clickme_vega(data,"lifelines",params=list(height=100,width=400,padding=list(top=60, left=5, bottom= 30, right=30)))

Monday, April 1, 2013

Old Price Tables in Modern d3 Visualization

In my post Dust off 130 Year Old Gold Books on Google Bookshelf, I reproduced some of the old and way out of copyright price tables from the appendices in Gold and Prices Since 1873 by James Laurence Laughlin using latticeExtra xyplot. Now, with the clickme multiline d3 ractive built in my last post “Building ractives is so addictive it should be illegal!”, we can easily transform this data into an interactive time series line chart.

I tried to generalize the multiline ractive to create almost any line chart for an xts object from R. See the commit history for the minor modifications that I made to the original ractive:

  1. Take data as given instead of transforming to a cumulative line
  2. Allow parameters for a title and the location of the x-axis
  3. Handle data series with differing start and end dates

We can build the html file using clickme with a couple of lines of R code.

# if not already installed, uncomment the two lines below
# library(devtools) install_github('clickme', 'nachocab')

require(clickme)
# set location where you put your multiline ractive
set_root_path("path to your ractive/r")
clickme(data = priceTables["1850::", c(-1, -6, -8, -11, -12)], ractive = "clickme_multiline_generic", 
params = list(title = "Price Tables from <em> Gold and Prices Since 1873 </em>",
x_axis_location = 100))

I had not seen an example of passing parameters, so I used title and x_axis_location as a test for how clickme handles parameters. If I read the source correctly, the template_config.yml specifies permissible parameters. Then the parameters can be specified by a list provided as params to the clickme function as shown above.

...
default_parameters: {
width: 960,
height: 500,
title,
x_axis_location
}
...

Live example


Git Repo

Wednesday, March 27, 2013

“Building ractives is so addictive it should be illegal!”

clickme is an amazing R package. I was not sure what to expect when I first saw Nacho Caballero's announcement. I actually was both skeptical and intimidated, but neither reaction was justified. The examples prove its power, and his wiki tutorials ease the noobie difficulties. Very similar to shiny, clickme serves as an integration point for html, javascript (especially d3), and R. While clickme does not allow the R websocket interactivity that shiny does, its more concentrated focus on quick reproducibility and sharing makes it a very useful tool. This is very much in the spirit of http://dexvis.wordpress.com/ Reusable Charts. ractives defined as

(short for interactives-a hat tip to Neal Stephenson), which are simple folder structures that contain a template file used to populate the JS code with R input data

provide the structure for clickme to produce an html file from

  1. a template in R markdown (template.rmd)
  2. a translator R script (translator.r)
  3. a data source
  4. external scripts (probably javascript) and styles (.css).

Inspired by the clickme longitudinal heatmap example, I just had to try to create my own ractive. I thought Mike Bostock's line chart example would serve as a nice template for my first ractive. The data not surprisingly will come from the R finance package PerformanceAnalytics dataset named managers. With very minor modifications to the Bostock source and a simple custom R script translator (translator.R shown below), we have everything we need for this ractive, which I will call multiline.

#' Translate the data object to the format expected by current template
#'
#' @param data input data object
#' @param opts options of current template
#' @return The opts variable with the opts$data variable filled in
translate <- function(data, opts = NULL) {
require(df2json)

# I would like to generalize this to handle both price and return right
# now just handles return clickme template.Rmd javascript can handle
# prices or cumulative so we will send cumulative which can serve as price

# remove na
data[is.na(data)] <- 0
# get cumulative growth
data <- cumprod(1 + data)


# convert to data frame
data.df <- data.frame(cbind(format(index(data), "%Y-%m-%d"), coredata(data)))
colnames(data.df)[1] = "date"
# melt the data frame so we have our data in long form
data.melt <- melt(data.df, id.vars = 1, stringsAsFactors = FALSE)
colnames(data.melt) <- c("date", "indexname", "price")
# remove periods from indexnames to prevent javascript confusion these .
# usually come from spaces in the colnames when melted
data.melt[, "indexname"] <- apply(matrix(data.melt[, "indexname"]), 2, gsub,
pattern = "[.]", replacement = "")
opts$data <- df2json(data.melt)
opts
}


Now to create our first clickme html page, we just need a couple lines of code in R.

# if not already installed, uncomment the tow lines below
# library(devtools) install_github('clickme', 'nachocab')

require(clickme)
# set location where you put your multiline ractive
set_root_path("your-path-goes-here/ractives")
require(PerformanceAnalytics)
data(managers) #although I use managers, really any xts series of returns will work
clickme(managers, "multiline")

Then, we have a web page that will create an interactive d3 line chart using the cumulative growth of the managers return series. If you do not see the embed below, then please follow the link.


Eventually, it will be very nice to have an entire gallery of amazing ractives.


git repo