You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 37 Current »

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 in Python.

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.

Page content

Implicit equation

Matplotlib does not have a specific function to plot implicit equations, but SymPy do. Try using SymPy and Symbolic mathematics when solving these exercises.

When using SymPy to create plots, Matplotlib is called, so make sure you have downloaded it already.

Exercise 1

Plot the equation

Read the documentation about plotting in SymPy.

Solution
from sympy import *

x, y = symbols('x y')
f = (y**2 + x**2 - 1)**3 - x**2*y**3

plot_implicit(f, (x, -1.5, 1.5), (y, -1.5, 1.5), title='<3')

Documentation about

Pie chart

Exercise 1: (Advanced) Pie chart with legend

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.

There are several ways to do this task, and the solution provided here is simply a suggestion. Should you happen to use a good alternative approach, please send us a mail and we will add it as a another suggested way of solving the task.

Below is a sketch of how you may present your figure:

Open the csv-file (comma-seperated value file) in notepad to see how the different columns are seperated.

Here are also some useful documentation regarding functions used in the solution:

Below is our suggested way of importing the data from the csv-file. Now it remains to plot the figure.

Hint 2
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]



Solution
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()

Some useful documentation regarding functions used:

The legend methods used/described in this exercise does not only apply to pie charts, but to most plots!

The legend methods used/described in this exercise does not only apply to pie charts, but to most plots!

Simple plot

Exercise 1: Fibonacci numbers part 1

Plot the 10 first Fibonacci numbers as a contionus line. The numbers are:

Solution
import numpy as np 
import matplotlib.pyplot as plt

fibNum = np.array([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])

plt.plot(fibNum)
plt.title("First 10 Fibonacci numbers")

plt.show()

Exercise 2: Fibonacci numbers part 2

Plot the 10 first Fibonacci numbers as independent dots. The numbers are:

Solution
import numpy as np 
import matplotlib.pyplot as plt

fibNum = np.array([0, 1, 1, 2, 3, 5, 8, 13, 21, 34])
# In addition to the Fibonacci numbers, we need to set an x-value when using scatter plot.
# We will use the order as our x-values, where the first number gets x-value equals 1, second equals 2 etc.
fibOrder = np.array(range(1, 11))   # 'range(1, 11)' returns an array from 1 to (but exept) 11.

plt.scatter(fibOrder, fibNum)
plt.title("First 10 Fibonacci numbers")

plt.show()

Functions used:



  • No labels