protovis part 4: external data and animated labels

Working with scales

One of our goals is to create templates that can be reused quickly. One of the most time-consuming adjustments for reusing a chart is changing the scale to fit inside the panel. Fortunately, Protovis has included a class called pv.Scale to make this more dynamic and eliminate your need to update most settings. Let's start by adding the variable dataRange and make it equal to 5000000. The highest population (or data value) is about 4.7 million, so dataRange will be used to set the scale on the chart.

Add a new variable called yScale that we'll use to distribute the bars vertically. Remember, we're going to flip the chart on its side. We'll use the pv.Scale class and define the scale as linear because the bars will be distributed along the Y axis. The scale starts at 0, then popbyrace.length counts how many elements make up the length of the data array and sets that number as the end point. Next we set the range of the bars in the panel with a start point of 0 and distribute the bars the height of the panel.

Nifty! Now lets use the same tool to define how each bar will stretch across the panel. Add a variable called total. This time, we're going to use pv.Scale to adjust the length of the bars based on the data values. The bars will start at 0 and extend to the value of the dataRange. Next it sets the width of the bars in the panel with a start point of 0 and extends the bars the width of the panel minus the leftMargin.

Add a variable called barWidth. Divide height by popbyrace.length (the number of elements in the data) to be sure all the bars fit in the panel.

Add a new variable called gap and set the value at 4. This will be used to set the gap between the bars.

Finally, change the height variable to 800 and we're ready to edit our chart.