Python and MatPlotLib: Creating a Pie Chart

This page is obsolete, I wrote it while I was just starting to learn python. I have wrote a much better set of notes on pandas available here:

Perquisites

Python

Pie Chart

We will create a basic pie chart consisting of 6 slices. In this case we will look at the top locations for British expats.

Python

To create the pie chart we can use:

Python

Exploding a Pie Wedge

It is also possible to explode each pie, by assigning a value between 0 and 1.

Python

Adding all the above lines of codes together in a script gives:

Python

Note in Python, by default when we run a script once again we will add a second pie chart on top of the original pie chart as shown above. To prevent this we will add the line under the perquisites:

Python

To give:

Python

The EU27 wedge is at 0.1. We can adjust the value of to explode the EU27 wedge to:

Python

Colour

To change the colour of wedges, we can use the additional input argument color (US spelling) and assign it to a list of RGB vectors, a list of Hexadecimal values or using the single letter and full names of primary and secondary colours. For more details about colours see:

Python

Often it is useful to split each colour onto its own line:

Python

Having all the data split onto multiple lines, we can easily read out the data for example for Canada as lines 3, 9, 15 and 21

Python

The plot command has to be updated to include the argument colors (US spelling):

Python

This gives:

Python

Wedge Properties – Line Width and Edge Colour

To get a black solid line of width 1.2 we can create a dictionary piewedgeprops

Python

And assign an additional input argument wedgeprops to this dictionary

Python

The code looks like the following:

Python

Adding the % Values to Each Pie Wedge

The input argument autopct can be used to assign percentage values to the pie segments:

Python

Using %f gives the percentage as a float:

Python

To get it ending in % we need to type in two % because the % is a special character:

Python

To change the nearest whole percent we add digits 1.0 between the % and the f:

Python

To get 1 decimal place we add instead 0.1

Python

To get to 2 decimal places we change the number to 0.2

Python

Wedge Properties – Wedge Hatching

To get some additional properties to fine tune, we need to set the piechart as a variable.

Python

As we can see the new variable mypie is a Tuple

We can index this to get the wedge properties:

Python

To alter the 0th edge property for example we use:

Python
Python

    agg_filter = None
    alpha = None
    animated = False
    antialiased or aa = True
    capstyle = butt
    children = []
    clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
    clip_on = False
    clip_path = None
    contains = None
    data_transform = CompositeGenericTransform(     TransformWrapper(  ...
    edgecolor or ec = (0.0, 0.0, 0.0, 1)
    extents = Bbox(x0=343.27874506813146, y0=247.03109138884946,...
    facecolor or fc = (0.0, 0.4392156862745098, 0.7529411764705882, 0.8)
    figure = Figure(640x480)
    fill = True
    gid = None
    hatch = None
    in_layout = True
    joinstyle = miter
    label = EU27
    linestyle or ls = -
    linewidth or lw = 1.2
    patch_transform = IdentityTransform()
    path = Path(array([[1.0770098 , 0.06379256],        [1.07...
    path_effects = []
    picker = None
    rasterized = None
    sketch_params = None
    snap = None
    transform = CompositeGenericTransform(     TransformWrapper(  ...
    transformed_clip_path_and_affine = (None, None)
    url = None
    verts = [[541.67874507 247.03109139]  [541.64722366 250.25...
    visible = True
    window_extent = Bbox(x0=343.27874506813146, y0=247.03109138884946,...
    zorder = 1
Python

We can also use set_property of any of the other properties in the list above.

Text Properties

We can instead select the edge by indexing into index 1 of mypie:

Once again we can use getp to look at the properties:

Python

    agg_filter = None
    alpha = None
    animated = False
    bbox_patch = None
    children = []
    clip_box = TransformedBbox(     Bbox(x0=0.0, y0=0.0, x1=1.0, ...
    clip_on = False
    clip_path = None
    color = black
    contains = None
    figure = Figure(640x474)
    fontfamily = ['sans-serif']
    fontname = DejaVu Sans
    fontproperties = :family=sans-serif:style=normal:variant=normal:wei...
    fontsize = 10.0
    fontstyle = normal
    fontvariant = normal
    fontweight = normal
    gid = None
    horizontalalignment = left
    in_layout = True
    label =
    path_effects = []
    picker = None
    position = (0.9241176452498854, 0.7655106646793416)
    prop_tup = (0.9241176452498854, 0.7655106646793416, 'EU27', '...
    rasterized = None
    rotation = 0.0
    rotation_mode = None
    sketch_params = None
    snap = None
    stretch = normal
    text = EU27
    transform = CompositeGenericTransform(     TransformWrapper(  ...
    transformed_clip_path_and_affine = (None, None)
    unitless_position = (0.9241176452498854, 0.7655106646793416)
    url = None
    usetex = False
    verticalalignment = center
    visible = True
    window_extent = Bbox(x0=462.9137832653213, y0=339.3884329578664, x...
    wrap = False
    zorder = 3

We can change the text of EU27 to European\nUnion which is European Union (over two lines), using a larger font size and angle:

Python

Once again we can use set_property to set the value of any properties in the list above.

Create a Donut Pie

To create a donut shaped pie, we can define a size and include this as the width within piewedgeprops which the input argument wedgeprops is assigned to. We also need to define the radius of the pie. In this case we will use 1 which is the default. For the radius of length of 1, this will give 0.7 of a hole and 0,3 if a rim.

Python
Python

Nested Piechart

We can create a nested piechart by using two donuts, the outer at radius 1 (line 43) and the inner at radius 1 minus the width, in the case 0.3 (line 44). In this case the labels of the inner piechart will overlap the pie segments of the outer piechart and in any case many of the labels are the same so only the outer labels are shown. An input argument of labeldistance=0.7 is used so small labels if included will be printed directly on the inner piesegment. In this piechart we want to keep related segments the same colour however we also want to distinguish them so line 48-53 changes the transparency of the inner pie segments. Line 54-56 adds the country abbreviations of Canada (C), Australia (A) and New Zealand (NZ).

Python
Advertisements

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.