Created
April 8, 2013 15:06
-
-
Save xuexue/5337499 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Data to be plotted | |
var prices = polyjs.data({ // prices of fruits | |
fruit: ['apple', 'banana', 'orange'], | |
price: [99, 79, 139] | |
}); | |
var sales = polyjs.data({ // sales of fruits | |
fruit: ['apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'apple', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'banana', 'orange', 'orange', 'orange', 'orange', 'orange', 'orange', 'orange'], | |
date: ['2013-04-01', '2013-04-02', '2013-04-03', '2013-04-04', '2013-04-05', '2013-04-06', '2013-04-07', '2013-04-01', '2013-04-02', '2013-04-03', '2013-04-04', '2013-04-05', '2013-04-06', '2013-04-07', '2013-04-01', '2013-04-02', '2013-04-03', '2013-04-04', '2013-04-05', '2013-04-06', '2013-04-07'], | |
sale: [20, 21, 26, 23, 19, 25, 15, 40, 52, 49, 43, 59, 41, 55, 30, 31, 33, 29, 25, 29, 35] | |
}); | |
// Helper function to assign a colour to a fruit | |
var color_fn = function(fruit) { | |
if (fruit == 'apple') { | |
return 'red'; | |
} else if (fruit == 'banana') { | |
return 'yellow' | |
} else { | |
return 'orange' | |
} | |
} | |
// Creating the charts by first generating the JSON spec, then the chart itself | |
var spec_prices = { | |
layer: { // bar chart of fruit prices | |
data: prices, | |
type: 'bar', | |
x: 'fruit', | |
y: 'price', | |
color: 'fruit' | |
}, | |
guide: { color: { scale: color_fn } }, // use the colour scale function defined earlier | |
dom: 'chart_prices', | |
width: 250, | |
height: 250, | |
title: 'Fruit Prices (Click on Bar)' | |
}; | |
var chart_prices = polyjs.chart(spec_prices); | |
var spec_sales = { | |
layer: { // line chart of sales of a particular fruit (default: apple) | |
data: sales, | |
type: 'line', | |
x: 'date', | |
y: 'sale', | |
color: {const: color_fn('apple')}, // default colour | |
size: {const: 3}, | |
filter: { fruit: { in: ['apple'] } } // filter the data so only apple sales are used | |
}, | |
guide: { | |
y: { min: 0, max: 6 } | |
}, // fix the y-axis min/max | |
dom: 'chart_sales', | |
title: 'Apple Sales (Click on Bar to Change Fruit)', | |
width: 400, | |
height: 250 | |
} | |
var chart_sales = polyjs.chart(spec_sales); | |
// Interaction! | |
chart_prices.addHandler(function(type, obj) { | |
if (type =='click' && obj.evtData.fruit) { | |
spec_sales.layer.filter.fruit = obj.evtData.fruit; // change the fruit (filter) | |
spec_sales.layer.color.const = color_fn(obj.evtData.fruit.in[0]); // change the colour | |
chart_sales.make(spec_sales); // re-render the chart (with default animations) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment