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=(0,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)" specifies the legends location
# "bbox_transform=plt.gcf().transFigure" makes sure our location specified in "bbox_to_anchor"
# is in reference to the reference system of the figure, not the axes (the actual pie)
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() |