Home > CoffeeScript, d3, d3js, data visualization > Visualizing Crime with d3: How to Make Bubbles and Influence People, Part 1

Visualizing Crime with d3: How to Make Bubbles and Influence People, Part 1

Previously:

  1. Visualizing Crime with d3: Intro
  2. Data and Visualization

In order to make a bubble chart in d3 (the one similar to the Obama Budget 2013), using CoffeeScript, you need to:

  1. Download a few files from my git hub (you’ll need coffee/BubbleChartSingle.coffee, css/visuals.css, css/colorbrewer.css)
  2. Define a class in a .coffee file:
    class @MyBubbleChart extends @BubbleChart
       constructor: (id, data, color) ->
          super(id, data, color)
    
  3. 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
    
  4. 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.:

    <div id='vis'></div>
    

    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)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: