In order to make a bubble chart in d3 (the one similar to the Obama Budget 2013), using CoffeeScript, you need to:
- Download a few files from my git hub (you’ll need coffee/BubbleChartSingle.coffee, css/visuals.css, css/colorbrewer.css)
- Define a class in a .coffee file:
class @MyBubbleChart extends @BubbleChart constructor: (id, data, color) -> super(id, data, color)
- I also define a couple of extensions to make life easier (in displayVis.coffee):
String::startsWith = (str) -> this.slice(0, str.length) == str String::removeLeadHash = () -> if this.startsWith("#") then this.slice(1) else this
- Finally, instantiate and display:
chart = new MyBubbleChart('vis', myArrayOfData, 'Spectral') chart.create_vis() chart.display()
Here ‘vis’ is the id of a container on your page where the visualization will go, e.g.:
myArrayOfData– is an array of your data,
'Spectral'– is a color scheme, one of many available from
colorbrewer.css, created by Cynthia Brewer. You can read about how this works here. Making colors for the visualization is a science in and of itself, since I am not versed in it, I am using someone else’s wonderful results.
And this it, you are done!
No, of course not, just kidding. There are a few more things to be tweaked in order for this to work. In particular, we need to observe a simple convention around the structure of our data records, define our own
color_class function so that the bubbles are colored meaningfully, and set some scaling parameters based on our data so that the circles fit nicely inside the container. It is also a good idea to bring in some tooltips to show when the user hovers over a bubble (or, for that matter, touches it on her tablet).
I will illustrate this with the crime example in the next post (the code is: coffee/AllStates.coffee)
One thought on “Visualizing Crime with d3: How to Make Bubbles and Influence People, Part 1”