Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Here, we will aim to provide you with a number of exercises and solutions with a varying degree of difficulty. There will also occur exercises that requires you to use functions that has not yet been described in Data visualization.

Info

If you have a suggestion on a topic you would like to see some more exercises (or tutorials) on, please send us a mail or leave a post on our Forum. We are more than happy to recieve feedback.



Panel
borderColor#dfe1e5
bgColor#eff9ff
borderWidth2
titlePage content

Table of Contents


Pie chart

Exercise 1: (Advanced) Pie chart with legend

Expand
titleExercise: Pie chart from Excel

Make a pie chart displaying the different political parties and their vote percentage in 2017. You are given a csv-file including all the necessary data: Stortingsvalg 2009 2013 2017.csv. To make the pie chart as pretty as possible, you are told to use the legend function when displaying the names of the political parties.

Expand
titleSolution: Pie chart from Excel


Code Block
languagepy
titleSolution
import matplotlib.pyplot as plt
import numpy as np 

# Opening the file, "r" is to specify that we want to read it
fid = open("Stortingsvalg 2009 2013 2017.csv", "r")

# Using "loadtxt" to import our data from the file
    # "dtype = "str"" defines the data as strings
    # "skiprows=3" makes us skip the 3 first lines, as they are useless to our problem
    # "usecols=3" makes us only read the first and fourth column, as we only need them in our data base
    # "delimiter=";"" sets the dilimiter that seperates our variabels.
        # That is because our csv-file (comma-seperated values file) is seperated by ";"
        # To doublecheck this, open up the csv-file in notepad.
data = np.loadtxt(fid, dtype='str', skiprows=3, usecols=(0, 3), delimiter=';')

# Closing the file
fid.close()

# The way we imported our data, the labels are stored in the first column,
    # and the number of votes in the second column
labels = data[:, 0]
votes = data[:, 1]

# Sets the title of our plot
plt.title('Stortingsvalg 2017')  

# Equal aspect ratio ensures that pie is drawn as a circle.  
plt.gca().axis("equal")    

# Plotting the pie chart:
    # "autopct" converts the values in terms of percentage
    # "startangle" sets the angle at which we starts the first "slice", in this case "Arbeiderpartiet"
pie = plt.pie(votes, autopct='%1.1f%%', startangle=0)

# "legend" is used to set the labels on the side, not around the pie
    # "labels" are the labels we want to display in our legend.
    # "fontsize" sets the size of the label text
    # "bbox_to_anchor=(1, 0.75)"
    # "bbox_transform=plt.gcf().transFigure" makes sure our location specified in "bbox_to_anchor" 
        # is in reference to reference system of the figure, not the axes   
plt.legend(labels, fontsize=10, bbox_to_anchor=(1, 0.75), bbox_transform=plt.gcf().transFigure)

# This section offsets the pie-figure to the left, in order to make space to display the legend
# Try removing/playing with this function and see what happens.
    # If removed, you will have to drag the pie away to show the legend.
plt.subplots_adjust(left=0.0, bottom=0.1, right=0.65)

# To make sure our data import is correct, I like to include the following "print(data)" as well
# print(data)

# Display our figure
plt.show()

Some useful documentation regarding functions used:





BibTeX Display Table