Exploiting matplotlib
Published in
4 min readMay 26, 2020
There are so many things to exploit man, but religion and patriotism are at the top of the list — Tarif Naaz, Mayhem In Paradise
Let’s cut to the chase.
Here is a very basic example of displaying basic graphs using matplotlib.
import matplotlib.pyplot as plt
data = {'apple': 10, 'orange': 15, 'lemon': 5, 'lime': 20}
names = list(data.keys())
values = list(data.values())
fig, axs = plt.subplots(1, 3, figsize=(9, 3), sharey=True)
axs[0].bar(names, values)
axs[1].scatter(names, values)
axs[2].plot(names, values)
fig.suptitle('Categorical Plotting')
Different kinds of graphs can be plotted based on the data we have and the information we want to display.
- Line Graph
- They are usually used to find relationship between two data sets on different axis; for instance X, Y.
import numpy as np
import matplotlib.pyplot as plt
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)plt.figure()
plt.plot(t1, f(t1), color='g', linestyle="--", label='Frequency')
plt.xlim(0, 7)
plt.ylim(1.2, -1.0);
plt.title("A Sample Line Curve")
plt.xlabel("x")
plt.ylabel("y")
plt.legend(loc='upper right')
plt.show()
2. Scatter Graph
%matplotlib inline
import matplotlib.pyplot as plt
plt.style.use('seaborn-whitegrid')
import numpy as nprs = np.random.RandomState(0)
x = rs.randn(100)
y = rs.randn(100)
colors = rs.rand(100)
sizes = 100 * rs.rand(100)plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')
plt.colorbar();
- An example would be to plot a population distribution against Lat/Long.
3. Contour 2D and 3D Graphs
%matplotlib inline
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import random
from matplotlib import cmdef fun(x, y):
return np.sin(x/3) + np.cos(y/4)fig = plt.figure(num=None, figsize=(7, 5), dpi=80, facecolor=’w’, edgecolor=’k’)
ax = plt.axes(projection=’3d’)x = y = np.arange(0, 25, 1)
X, Y = np.meshgrid(x, y)
zs = np.array(fun(np.ravel(X), np.ravel(Y)))
Z = zs.reshape(X.shape)ax.plot_surface(X, Y, Z, cmap=’viridis’)ax.set_xlabel(‘X’)
ax.set_ylabel(‘Y’)
ax.set_zlabel(‘Z’)
plt.show()ax.view_init(60, 35)
plt.show()plt.figure(figsize=(7, 5), dpi=80, facecolor=’w’, edgecolor=’k’)
contours = plt.contour(X, Y, Z, 3, colors=’black’)
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(Z, extent=[0, 25, 0, 25], origin=’lower’,
cmap=’viridis’, alpha=0.5)
plt.colorbar();
- Helpful in visualising distribution of certain attribute such as density/potential difference/ brightness.
4. Histogram
- It is used to summarise discrete or continuous data.
- It is similar to a Bar Chart, but a histogram groups numbers into ranges .
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')data = np.random.randn(1000)x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)kwargs = dict(histtype='stepfilled', alpha=0.6, density=True, bins=40)plt.hist(x1, **kwargs)
plt.hist(x2, **kwargs);
5. Boxplot
- Boxplot is probably one of the most common type of graphic.
- The line that divides the box into 2 parts represents the median of the data.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt# fake up some data
spread = np.random.rand(50) * 100
center = np.ones(25) * 20
flier_high = np.random.rand(10) * 20 + 100
flier_low = np.random.rand(5) * (-20)
data = np.concatenate((spread, center, flier_high, flier_low))fig1, ax1 = plt.subplots()
ax1.set_title('Basic Plot')
ax1.boxplot(data);
- It is more convenient to use seaborn due to variety of visualisation patterns, but again under the hood its just matplotlib.
- It would be nicer to get your hands dirty with some practical data visualisation and explore more apis of matplotlib. You can find a lot of notebooks on kaggle adhering to the same.
That’s all for now folks. Thanks for reading.
Special Credits to: