Read Documentation for details: https://matplotlib.org/stable/users/index.html
To begin, let's install the Matplotlib library. We'll use the matplotlib.pyplot
module for basic plots like line & bar charts. It is often imported with the alias plt
.
# To install this library in Jupyter notebook
import sys
#!{sys.executable} -m pip install --upgrade pip
!{sys.executable} -m pip install matplotlib --quiet
import matplotlib
matplotlib.__version__ , matplotlib.__path__
('3.4.3', ['/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/matplotlib'])
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
import numpy as np
mks = np.array([65, 85, 72,45, 87, 68, 61, 80, 77, 73, 66, 200])
# Create figure and axes objects
fig, ax = plt.subplots()
ax.boxplot(x=mks, patch_artist=True)
# title and axis labels
ax.set_title('Box Plot for Subject Marks')
ax.set_xlabel('Data Science')
ax.set_ylabel('Marks')
# add horizontal grid lines
ax.yaxis.grid(True)
print("Mean: ", np.median(mks))
print("Min: ", np.max(mks))
print("Min: ", np.min(mks))
q1, q2, q3 = np.quantile(mks,[.25, .5, .75])
print("Q1:", q1)
print("Q2:", q2)
print("Q3:", q3)
plt.show()
Mean: 72.5 Min: 200 Min: 45 Q1: 65.75 Q2: 72.5 Q3: 81.25
import pandas as pd
df = pd.read_csv("datasets/boxplot.csv")
df.head()
rollno | name | address | gender | group | session | age | scholarship | machine_learning | data_science | big_data | |
---|---|---|---|---|---|---|---|---|---|---|---|
0 | MS01 | SAADIA | Lahore | female | group B | MORNING | 28 | 2562 | 33 | 81 | 74 |
1 | MS02 | JUMAIMA | Islamabad | female | group C | AFTERNOON | 33 | 2800 | 27 | 90 | 88 |
2 | MS03 | ARIFA | Karachi | female | group A | EVENING | 34 | 3500 | 24 | 95 | 93 |
3 | MS04 | SAADIA | Lahore | female | group A | MOR | 44 | 2000 | 37 | 57 | 44 |
4 | MS05 | DANISH | Peshawer | male | group C | AFTERNOON | 54 | 2100 | 39 | 78 | 55 |
df.shape
(50, 11)
df.data_science.min()
42
df.data_science.max()
95
df.data_science.median()
70.0
# measuring quantiles for Data Science
df.data_science.quantile([.25, .5, .75])
0.25 57.25 0.50 70.00 0.75 77.25 Name: data_science, dtype: float64
In Matplotlib, boxplot()
is the core function to create box plot. Below are some of the important parameters of the function:
x
: Array or a sequence of vectors. The input data.vert
: Set as True or False. The default value is True, which displays the boxes vertically.labels
: Sets the labels for each dataset.notch
: Set as True or False. the default value is False. If True, the parameter will produce a notched box plot.widths
: Sets the width of the box.patch_artist
: Set as True or False. the default value is False. If False, the parameter will produce boxes with the Line2D artist. Otherwise, the boxes will be drawn with Patch artists.
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
# Create figure and axes objects
fig = plt.figure()
ax = fig.add_subplot()
# Get the dataset(s)
machine_learning = list(df['machine_learning'])
data_science = list(df['data_science'])
big_data = list(df['big_data'])
values = [machine_learning, data_science, big_data]
xlabels=["Machine Learning", "Data Science", "Big Data"]
ax.boxplot(x=values, patch_artist=True, labels = xlabels)
# title and axis labels
ax.set_title('Box Plot for Subject Marks')
ax.set_xlabel('Subjects')
ax.set_ylabel('Marks')
# add horizontal grid lines
ax.yaxis.grid(True)
plt.show()
Violin plots are similar to box plots, except that they also show the probability density of the data at different values. These plots include a marker for the median of the data and a box indicating the interquartile range, as in the standard box plots.
A violin plot is more informative than a plain box plot. In fact while a box plot only shows summary statistics such as mean/median and interquartile ranges, the violin plot shows the full distribution of the data.
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt
# Create figure and axes objects
fig = plt.figure()
ax = fig.add_subplot()
# Get the dataset(s)
machine_learning = list(df['machine_learning'])
data_science = list(df['data_science'])
big_data = list(df['big_data'])
values = [machine_learning, data_science, big_data]
xlabels=["Machine Learning", "Data Science", "Big Data"]
quantiles= [[0.25,0.75], [0.25,0.75], [0.25,0.75]]
ax.violinplot(dataset=values, showmedians=True, quantiles=quantiles)
# title and axis labels
ax.set_title('Violin Plot for Subject Marks')
ax.set_xlabel('Subjects')
ax.set_ylabel('Marks')
ax.set_xticks([1,2,3])
ax.set_xticklabels(xlabels)
# add horizontal grid lines
ax.yaxis.grid(True)
plt.show()
Heat map Heat map is used to find out the correlation between different features in the dataset.High positive or negative value shows that the features have high correlation.This helps us to select the parmeters for machine learning.
- A heatmap is a useful chart that we can use to show the relationship between two variables.
- A heatmap is used to visualize 2-dimensional data like a matrix or a table using colors.
import numpy as np
data_set = np.random.randint(0 , 255, 250000).reshape(500,500)
data_set
array([[132, 140, 154, ..., 230, 189, 244], [187, 76, 217, ..., 197, 72, 148], [132, 253, 87, ..., 4, 72, 86], ..., [105, 214, 90, ..., 202, 115, 76], [249, 8, 147, ..., 131, 24, 95], [ 42, 94, 36, ..., 228, 130, 212]])
plt.imshow(X=data_set)
plt.colorbar()
plt.title( "2-D Heat Map" )
plt.show()
plt.imshow(X=data_set, cmap='gray')
plt.colorbar()
plt.title( "2-D Heat Map" )
plt.show()
plt.imshow(X=data_set, cmap='coolwarm', interpolation='nearest')
plt.colorbar()
plt.title( "2-D Heat Map" )
plt.show()
plt.imshow(X=data_set, cmap='coolwarm', interpolation='bicubic')
plt.colorbar()
plt.title( "2-D Heat Map" )
plt.show()
from PIL import Image
rgb_img = Image.open("datasets/speech.jpg")
grey_img = rgb_img.convert('L')
rgb_img_array = np.array(grey_img)
plt.imshow(X=rgb_img_array, cmap='gray')
plt.colorbar()
plt.title( "2-D Heat Map" )
#grey_img.shape
plt.show()
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /var/folders/1t/g3ylw8h50cjdqmk5d6jh1qmm0000gn/T/ipykernel_37453/3336010265.py in <module> 7 plt.colorbar() 8 plt.title( "2-D Heat Map" ) ----> 9 grey_img.shape 10 plt.show() /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/PIL/Image.py in __getattr__(self, name) 544 ) 545 return self._category --> 546 raise AttributeError(name) 547 548 @property AttributeError: shape
plt.subplot()
fig.add_subplot()
plt.subplots()
plt.subplots()
method, and specify the number of rows and columns as shown below:fig, <ax objects> = plt.subplots(rows, cols)
<ax objects>
needs to have dimensions that correspond to rows and cols.plt.subplots()
method unlike the other two methods return an array of axes, so you can access different axes objects using following two ways:plt.gca()
), so when you call the plot
function, it draws on the active subplot.If a 2 row by 2 column array of plots is created, the
fig, ( (ax1,ax2), (ax3,ax4) ) = plt.subplots(2,2)
If a 2 row by 3 column array of plots is created, the
fig, ( (ax1,ax2,a3), (ax4,ax5,ax6) ) = plt.subplots(2, 3)
Option 1: plt.subplot()
# The third argument of the `plt.subplot()` method mentions the specific axes object to create in the grid
# It starts from 1, then left to right, and top to bottom
fig = plt.figure()
ax1=plt.subplot(2,2,1)
ax2=plt.subplot(2,2,2)
ax3=plt.subplot(2,2,3)
ax4=plt.subplot(2,2,4)
Option 2: fig.add_subplot()
# The third argument of the `fig.add_subplot()` method mentions the specific axes object to create in the grid
# It starts from 1, then left to right, and top to bottom
fig = plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)
ax4=fig.add_subplot(2,2,4)
Option 3: plt.subplots()
# There is no third argument to `plt.subplots()` method, as it creates all axes objects in just one line
# and return all the axes objects which you can receive in either an array or tupples
fig,ax = plt.subplots(2,2)
#Now you can access the subplots using subscript operator e.g., ax[0][0], ax[0][1], ax[1][0], and ax[1][1]
# There is no third argument to `plt.subplots()` method, as it creates all axes objects in just one line
# and return all the axes objects which you can receive in either an array or tupples
fig,((ax1,ax2),(ax3,ax4)) = plt.subplots(2,2)
#Now you can access the subplots using the names ax1, ax2, ax3, ax4
We will be using the
plt.subplots()
method to create subplots
So lets do a bit of more practice
fig,ax = plt.subplots()
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2)
fig, (ax1,ax2) = plt.subplots(nrows=2,ncols=1)
fig, (ax1,ax2) = plt.subplots(nrows=1,ncols=2)
fig, ((ax1,ax2), (ax3,ax4)) = plt.subplots(nrows=2,ncols=2)
fig, ( (ax1,ax2,ax3), (ax4,ax5,ax6) ) = plt.subplots(2, 3)
fig, ( (ax1,ax2), (ax3, ax4), (ax5,ax6) ) = plt.subplots(3, 2)
# Another way is to receive all the axes in a single variable and later use it as an array of axes
fig, ax = plt.subplots(3, 3)
- In above grid,
ax[0][2]
will represent the right most axes in the zeroth row- In above grid,
ax[1][1]
will represent the middle axes object in below grid
Example 1:
import numpy as np
x = np.linspace(-1, 1, 30)
x
array([-1. , -0.93103448, -0.86206897, -0.79310345, -0.72413793, -0.65517241, -0.5862069 , -0.51724138, -0.44827586, -0.37931034, -0.31034483, -0.24137931, -0.17241379, -0.10344828, -0.03448276, 0.03448276, 0.10344828, 0.17241379, 0.24137931, 0.31034483, 0.37931034, 0.44827586, 0.51724138, 0.5862069 , 0.65517241, 0.72413793, 0.79310345, 0.86206897, 0.93103448, 1. ])
x = np.linspace(-1, 1, 30)
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
ax1.plot(x,x) # 1st subplot = top left
ax2.plot(x, x**2) # 2nd subplot = top right
ax3.plot(x,x**3) # 3rd subplot = bottom left
ax4.plot(x,x**4) # 4th subplot = bottom right
plt.show()
x = np.linspace(-1, 1, 30)
fig, ax = plt.subplots(2, 2)
ax[0][0].plot(x,x) # 1st subplot = top left
ax[0][1].plot(x, x**2) # 2nd subplot = top right
ax[1][0].plot(x,x**3) # 3rd subplot = bottom left
ax[1][1].plot(x,x**4) # 4th subplot = bottom right
plt.show()
Example 2:
from matplotlib import pyplot as plt
chemical_exports = [0.810, 0.831, 0.895, 0.91, 0.915, 0.926, 0.945, 0.931, 0.919, 0.921, 0.920, 0.919]
years = [2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021]
medicine_exports = [0.791, 0.818, 0.832, 0.816, 0.840, 0.833, 0.835, 0.838, 0.842, 0.910, 0.930, 0.940]
fig, (ax1,ax2) = plt.subplots(nrows=2, ncols=1)
ax1.plot(years, chemical_exports, label='Chemicals', marker='o', c='b', ls='-', lw=2)
ax2.plot(years, medicine_exports, label='Medicines', marker='x', c='r', ls=':', lw=2)
#Note the use of `set_`
ax1.set_title("LCI Chemical exports in last 12 years")
ax1.set_xlabel("Years")
ax1.set_ylabel("Amount (Million Rs.)")
ax2.set_title("LCI Medicine exports in last 12 years")
ax2.set_xlabel("Years")
ax2.set_ylabel("Amount (Million Rs.)")
plt.tight_layout()
plt.show()
Example 3:
import matplotlib.pyplot as plt
import numpy as np
# geerating random values withing range from a univariate “normal” (Gaussian) distribution of mean 0 and variance 1.
data = np.random.randn(2000)
fig, ax = plt.subplots(nrows=2, ncols=2)
# use axes object to plot histograms in subplots, for example plot histrogram on 0th row, 0th column
ax[0][0].hist(data, bins=30)
ax[0][0].set_title("set bins=30")
# plot histrogram on 0th row, 1st column, by setting density to true which normalized the histogram
ax[0][1].hist(data, density=True, color="r")
ax[0][1].set_title("normalized")
# plot histrogram on 1st row, 0th column,
ax[1][0].hist(data, color="orange")
ax[1][0].set_title("set color as Oranges")
# plot histrogram on 1st row, 1st column, by setting histogram type as step
ax[1][1].hist(data, histtype='step')
ax[1][1].set_title("step")
plt.tight_layout()
plt.show()
Example 4:
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
# import iris dataset and display in dataframe
df_iris = sns.load_dataset('iris')
fig, axes = plt.subplots(nrows=2, ncols=2, dpi=100)
# draw line plot on iris data (between dataframe index and sepal_length column)
axes[0][0].plot(df_iris.index, df_iris['sepal_length'], color='r')
axes[0][0].grid(True)
axes[0][0].set_facecolor('#FAEBD7')
# draw bar-plot on iris data (between dataframe index and sepal_length column)
axes[0][1].bar(df_iris.index, df_iris['sepal_length'])
# draw scatter-plot on iris data (between sepal_length and sepal_width column)
axes[1][0].scatter(df_iris['sepal_width'], df_iris['sepal_length'], color='orange')
axes[1][0].grid(True)
axes[1][0].set_facecolor('#BDEFE9')
# draw histogram-plot on iris data (on sepal_length column)
axes[1][1].hist(df_iris['sepal_length'], bins=20, density=True, histtype='bar', alpha=0.3,
color='green', edgecolor='black')
axes[1][1].grid(True)
plt.show()
import numpy as np
import matplotlib
from matplotlib import pyplot as plt
import seaborn as sns
# import iris dataset and display in dataframe
df_iris = sns.load_dataset('iris')
fig, axes = plt.subplots(nrows=2, ncols=2, dpi=100)
# draw line plot on iris data (between dataframe index and sepal_length column)
axes[0][0].plot(df_iris.index, df_iris['sepal_length'], color='r')
axes[0][0].grid(True)
# draw bar-plot on iris data (between dataframe index and sepal_length column)
axes[0][1].bar(df_iris.index, df_iris['sepal_length'])
# draw scatter-plot on iris data (between sepal_length and sepal_width column)
axes[1][0].scatter(df_iris['sepal_width'], df_iris['sepal_length'], color='orange')
axes[1][0].grid(True)
# draw histogram-plot on iris data (on sepal_length column)
axes[1][1].hist(df_iris['sepal_length'], bins=20, density=True, histtype='bar', alpha=0.3,
color='green', edgecolor='black')
plt.show()