Chapter 4. Advanced Charts

In this chapter, we will explore and build some more advanced SVG charts using the pygal charting library for Python. We will also explore the worldmap chart with pygal and explore data types that are specific to that chart.

Pie charts

Pie charts work well with displaying data of a group or the total sum of a set of data, which is broken out like a pie. Let's build a simple pie chart with some dummy data. Take a look at the following code and incorporate it into your own Python file. Note that we are saving the file output to pie_chart.svg this time:

# -*- coding: utf-8 -*-
import pygal

pie_chart = pygal.Pie()
pie_chart.title = 'Total top tablet sales in 2013 (in %)'
pie_chart.add('iPad & iPad mini', 49.7)
pie_chart.add('Surface Pro 2', 36.3)
pie_chart.add('Surface 2', 24.5)
pie_chart.add('Nexus 7', 17.5)

pie_chart.render_to_file('pie_chart.svg')

The following screenshot shows you the results of our script:

Pie charts

As we can see in the preceding chart, each add() function to the pie chart adds a different device as a slice to the pie chart. The pie function also includes our standard legend based on the string given in our first parameter.

Stacked pie charts

Stacked pie charts work just as they sound; they stack values in each slice of the pie chart, giving you a more in-depth look at data. As stacked charts can include multiple values that aren't a part of the pie as a whole, we will build this chart without checking for errors. Let's build our chart with the following code sample; notice that we are still using the Pie() function, which is similar to our scatter plot and XY charts from the previous chapter. One limitation is that stacked pie charts in pygal only accept one other value on top of the main value. We can also use single values as shown on the Nexus 7 dataset. This is shown in the following code:

# -*- coding: utf-8 -*-
import pygal
pie_chart = pygal.Pie()
pie_chart.title = 'Total top tablet sales in 2013 (in %)'
pie_chart.add('iPad & iPad mini', [19.7, 21.3])
pie_chart.add('Surface 2 (& Pro 2)', [24.5, 36.3])
pie_chart.add('Nexus 7', 17.5)

pie_chart.render_to_file('pie_chart.svg')

Open the pie_chart.svg file and the result will be as shown in the following screenshot:

Stacked pie charts

In the preceding example, we can see the sublayer slices within each pie slice. Taking a look at our code sample, notice that the extra slice comes from the Python list array inside our second parameter for each add() function that we add to our chart object.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5