Customizing Matplotlib
Customizing Matplotlib
Syntax: legend(loc = ’ ‘)
The loc attribute takes the following value.
upper left, upper right, lower left, lower right, upper center, lower center,
center left, center right, center, best.
Multiple Legends
Sometimes when designing a plot you’d like to add multiple legends to the same axes.
Matplotlib does not make this easy. If you try to create a second legend it will simply
override the first one.
Ex:
leg = plt.Legend(ax, lines[2:], ['line C', 'line D'], loc='lower right', frameon=False)
ax.add_artist(leg)
---
CUSTOMIZING COLORBARS
plt.xlabel('x-axis')
plt.ylabel('y-axis')
# Normalizer
norm = mpl.colors.Normalize(vmin=0, vmax=2)
# creating ScalarMappable
sm = plt.cm.ScalarMappable(cmap=cmap, norm=norm)
sm.set_array([])
plt.colorbar(sm, ticks=np.linspace(0, 2, N))
plt.show()
Color limits and extensions
The colorbar itself is simply an instance of plt.Axes. We can narrow the color limits
and indicate the out-of-bounds values with a triangular arrow at the top and bottom by setting
the extend property.
Ex:
plt.subplot(1, 2, 1)
plt.imshow(I, cmap='RdBu')
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(I, cmap='RdBu')
plt.colorbar(extend='both')
plt.clim(-1, 1);
Discrete colorbars
Colormaps are by default continuous, but sometimes you’d like to represent discrete
values. The easiest way to do this is to use the plt.cm.get_cmap() function, and pass the name
of a suitable colormap.
Ex:
plt.imshow(I, cmap=plt.cm.get_cmap('Blues', 6))
plt.colorbar()
plt.clim(-1, 1)
---
It is possible to add texts over matplotlib charts by using the text functions.
Syntax:
text(x, y, s, fontdict=None, **kwargs)
x,y - The position to place the text.
s - The text.
fontdict - A dictionary to override the default text properties. (default: None)
**kwargs - Text Properties. (alpha, color, backgroundcolor, …)
Ex:
import matplotlib.pyplot as plt
x = [1, 2, 4]
x_pos = 0.5
y_pos = 3
Ex:
plt.text(1, 5, ". Data: (1, 5)", transform=plt.transData)
plt.text(0.5, 0.1, ". Axes: (0.5, 0.1)", transform=plt.transAxes)
plt.text(0.2, 0.2, ". Figure: (0.2, 0.2)", transform=fig.transFigure)
Arrows and Annotation
Annotations are similar to basic texts, but the annotate function provides further
parameters to annotate specific parts of the plot with arrows. The plt.annotate() function is used
to create some text and an arrow.
Syntax:
Ex:
import numpy as np
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(np.sin(np.linspace(0, 10)))
plt.annotate('Minimum', xy = (23, -0.95), xytext = (23, 0.25),
arrowprops = dict(facecolor = 'black', width = 0.2, headwidth = 8),
horizontalalignment = 'center')
plt.show()
---
Customizing the plot means changing the default settings to make it look a little bit
nicer. This customization can be done in different ways.
Stylesheets
Another way to change the visual appearance of plots is to set the rcParams in a so-
called style sheet and import that style sheet with matplotlib.style.use. In this way you can
switch easily between different styles by simply changing the imported style sheet. A style
sheets looks the same as a matplotlibrc file, but in a style sheet you can only set rcParams that
are related to the actual style of a plot.
The available styles are listed in ‘plt.style.available’. The basic way to switch to a
stylesheet is to call plt.style.use('stylename'). This will change the style for the rest of the
session.
You can use the style context manager, which sets a style temporarily.
Ex:
Changing the graphics to bold colors, thick lines, and transparent axes.
with plt.style.context('fivethirtyeight'):
hist_and_lines()
with plt.style.context('ggplot'):
hist_and_lines()
---
THREE-DIMENSIONAL PLOTTING IN MATPLOTLIB
Matplotlib was initially designed with only two-dimensional plotting in mind. Around
the time of the 1.0 release, some three-dimensional plotting utilities were built on top of
Matplotlib’s two-dimensional. The result is a convenient set of tools for three-dimensional data
visualization. We can enable three-dimensional plots by importing the mplot3d. Once this
submodule is imported, we can create a three-dimensional axes by passing the keyword
projection='3d' to any of the normal axes creations.
Ex:
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.axes(projection='3d')
Ex:
ax = plt.axes(projection='3d')
# Data for a three-dimensional line
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
ax.plot3D(xline, yline, zline, 'gray')
# Data for three-dimensional scattered points
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
ax.scatter3D(xdata, ydata, zdata, c=zdata, cmap='Greens');
Ex:
def f(x, y):
return np.sin(np.sqrt(x ** 2 + y ** 2))
x = np.linspace(-6, 6, 30)
y = np.linspace(-6, 6, 30)
X, Y = np.meshgrid(x, y)
Z = f(X, Y)
fig = plt.figure()
ax = plt.axes(projection='3d')
ax.contour3D(X, Y, Z, 50, cmap='binary')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z');
To change the viewing angle view_init method is used. This can be done by setting the
elevation and azimuthal angles. In the below example the values are set as elevation = 60
degrees (that is, 60 degrees above the x-y plane) and an azimuth = 35 degrees (that is, rotated
35 degrees counter-clockwise about the z-axis).
ax.view_init(60, 35)
Surface Triangulations
The function ax.plot_trisurf() helps us in creating a surface by first finding a set of
triangles formed between adjacent points.
Ex:
ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, z,cmap='viridis', edgecolor='none')
---
Ex:
Seaborn scatter plots
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
# customize the scatter plot
sns.scatterplot(x="total_bill", y="tip", hue="sex", size="size", sizes=(50, 200), data=tips)
# add labels and title
plt.xlabel("Total Bill")
plt.ylabel("Tip")
plt.title("Relationship between Total Bill and Tip")
# display the plot
plt.show()
---