Matplotlib Cheat Sheet đ
Part 2
The most common type of graph is the bar graph because of its ease in viewing categorical data. Bar graphs are fairly easy to construct and only require a few arguments.
Making the bar graph horizontal is as easy as plt.barh( ). Letâs add one more attribute to our graphs in order to depict the amount of variance.
The xerr= allows us to indicate the amount of variance per sector value. If need be yerr= is also an option.
Next we will create a stacked bar graph. It may appear that there is a lot of code for this graph but try your best to go through it slowly and remember all the steps we took while creating every graph until now.
sectors = [âSec 1â,âSec 2',âSec 3',âSec 4',âSec 5']
sector_values = [ 23 , 45 , 17 , 32 , 29 ]
subsector_values = [ 20 , 40 , 20 , 30 , 30 ]index = np.arange(5)
width = 0.30plt.bar(index, sector_values, width, color = âgreenâ, label = âsector_valuesâ)plt.bar(index + width, subsector_values,width, color = âblueâ, label = âsubsector_valuesâ)plt.title(âHorizontally Stacked Barsâ)
plt.xlabel(âSectorsâ)
plt.ylabel(âSector Valuesâ)plt.xticks(index + width/2 , sectors)plt.legend(loc = âbestâ)
plt.show()
Without making much modification to our code we can stack our bar graphs one atop the other by indicating, for example, bottom = sector_values within the plt.bar() method of the plot that we want to be on top. Be sure to get rid of the width variable and any instance where it was called further down into our code.
Next letâs create a pie chart. This is done easily by using the pie( ) method. We will start with a simple chart then add modifying attributes to make it more unique. Again donât be overwhelmed with the amount of code that this chart requires.
Histograms are used to plot the frequency of score occurrences in a continuous dataset that have been divided into classes called bins. In order to create our dataset we are going to use the numpy function np.random.randn. This will generate data with the properties of a normal distribution curve.
Finally lets talk about scatter plots and 3D plotting.
Scatter plots are vert useful when dealing with a regression problem. In order to create our scatter plot we are going to create an arbitrary set of height and weight data and plot them against each other.
This same scatterplot can also be visualized in 3D. To do this we are going to first import the mplot3d module as follows:
from mpl_toolkits import mplot3d
Next we need to create the variable ax that is set equal to our projection type.
ax = plt.axes( projection = â3dâ)
The following code is fairly repetitive of what youâve seen before.
Well if youâve made it this far you should be proud of yourself. Weâve only gone through the basics of what matplotlib is capable of but, as youâve noticed, there is a bit of a trend in how plots are created and executed. Check out the Matplotlib Sample Plots page in order to see the many more plots Matplotlib is capable of.
Next we will discuss Seaborn.