Quinn Alexa Royer's

Online Portfolio

Pie Chart

Figure 1
Figure 2

Entering Data

The data and options are included within a JavaScript object. The data attribute contains the data for each slice of the pie chart. The example in figure 1 has a value of [1,4,3,2,7] for data. The program adds up the values to get the total, then figures out the percentage of each slice as a fraction of a total.

The names of each slice are the value for the names attribute. The order of the entries in data and names attributes determine which name corresponds with which data. In other words, the nth value of names determines the name of the slice for the nth element of data.

Colors

The colors are entered as an array value for the colors attribute. names determines the color of the slice for the nth element of data, and the nth value of names is the name for the nth element of data. Like the names attribute, the nth entry of colors determines the color of the slice corresponding to the nth element of data. If there are fewer colors then there are data entries, it will cycle back to the beginning of the colors array. The code below creates the chart in figure 2:

var info = {data:[30.1, 17.6, 12.5, 9.7, 7.9, 6.7, 5.8, 5.1, 4.6], colors:["red","green","blue"], names:["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine"] }; var element = d3.select("#chart"); var c = new PieChart(element, info);

Here, there are nine slices but three colors (red, green, and blue), so the slices cycle between the three colors.