0% found this document useful (0 votes)
19 views

Customizing Matplotlib

Unit 4 data science

Uploaded by

bonamkotaiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Customizing Matplotlib

Unit 4 data science

Uploaded by

bonamkotaiah
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

CUSTOMIZING MATPLOTLIB

CUSTOMIZING PLOT LEGENDS


Legend is an area of the plot describing each part of the plot. The legend is made more
readable and recognizable by adding font, origin, and other details. The simplest legend can be
created with the plt.legend() command. We can customize the legend in different ways.

Changing the legend position:


The position of the legend in the plot can be changed by specifying loc attribute in the
legend function.

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.

Ex: plt.legend(loc=’upper left’)

Turnoff the frame


The frame over the legends can be turned off by using ‘frameon=false’.
Ex: plt. legend(loc='upper left', frameon=False)

Specifying the number of columns in the legend


Ex:
plt. legend(frameon=False, loc='lower center', ncol=2)
Specifying the Title
The title parameter will let us give a title for the legend and the title_size specifies
fontsize for the title.
Ex:
plt.legend(loc='upper right', title='Trigonometric Functions', facecolor='lightgrey',
labelcolor='black')

Adding fancy box and shadow


shadow -> This argument gives shadow behind the legend.
fancybox -> Gives round edges to the legend.
framealpha -> Gives transparency to legend background.
Ex:
plt. legend(fancybox=True, framealpha=1, shadow=True, borderpad=1)

Choosing Elements for the Legend


The legend includes all labeled elements by default. We can fine-tune which elements
and labels appear in the legend by using the objects returned by plot commands.
The plt.plot() command is able to create multiple lines at once, and returns a list of
created line instances (lines). Passing these values to plt.legend() will tell which to identify.
Applying labels to the plot elements.
Ex: plt.plot(x, y[:, 0], label='first')
plt.plot(x, y[:, 1], label='second')

Legend for Size of Points


Sometimes we’d like a legend that specifies the scale of the sizes of the points.
Ex:
for area in [100, 300, 500]:
plt.scatter([], [], c='k', alpha=0.3, s=area, label=str(area) + ' km$^2$')
plt.legend(scatterpoints=1, frameon=False, labelspacing=1, title='City Area')

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

The colorbar() function in pyplot module of matplotlib adds a colorbar to a plot


indicating the color scale. It is a separate axes that provides a key for the meaning of colors in
a plot. The simplest colorbar can be created with the plt.colorbar function.
Ex: plt.colorbar()

Adding a horizontal colorbar to a scatterplot


To make a colorbar horizontal we can use orientation in the function.
Ex:
plt.scatter(x=purchaseCount, y=likes, c=ratio, cmap="summer")
plt.colorbar(label="Like/Dislike Ratio", orientation="horizontal")
plt.show()

Adding a single colorbar to multiple subplots


The plt.colorbar() function, allows you to easily add a colorbar to the set of subplots.
Ex:
import matplotlib.pyplot as plt
# creates four Axes
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
im = ax.imshow(np.random.random((10, 10)), vmin=0, vmax=1)
plt.colorbar(im, ax=axes.ravel().tolist())
plt.show()

Adding colorbar to a non-mappable object

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)

---

TEXT AND ANNOTATION


Text

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

plt.text(x_pos, y_pos, "text on plot")


plt.plot(x)
plt.show()
The keywords argument in the text () function specifies the color, size, style, alignment, and
other properties.

Transforms and Text Position


We can anchor the text annotations to data locations in the plot. Sometimes it is
preferable to anchor the text to a position on the axes or figure, independent of the data. This
can be done by modifying the transform property.

There are three predefined transforms that can be useful:


i) ax.transData
Transform associated with data coordinates
ii) ax.transAxes
Transform associated with the axes (in units of axes dimensions)
iii) fig.transFigure
Transform associated with the figure (in units of figure dimensions)

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:

annotate(text, xy, xytext=None, xycoords='data', textcoords=None, arrowprops=None,


annotation_clip=None, **kwargs)

text - The text of the annotation.


xy - The point (x, y) to annotate.
xytext - The position (x, y) to place the text at.
arrowprops - dict, The properties used to draw a FancyArrowPatch arrow between
the positions xy and xytext.

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 MATPLOTLIB: CONFIGURATIONS AND STYLESHEETS

Customizing the plot means changing the default settings to make it look a little bit
nicer. This customization can be done in different ways.

Plot Customization by Hand


We can customize the plot by hand to make it a much more visually pleasing plot.
Ex:
# draw solid white grid lines
plt.grid(color='w', linestyle='solid')

# control face and edge color of histogram


ax.hist(x, edgecolor='#E6E6E6', color='#EE6666');

# hide axis spines


for spine in ax.spines.values():
spine.set_visible(False)

Changing the Defaults: rcParams


Each time Matplotlib loads, it defines a runtime configuration (rc). It containing the
default styles for every plot element you create. All rc settings are stored in a dictionary-like
variable called matplotlib.rcParams, which is global to the matplotlib package. You can adjust
this configuration at any time using the plt.rc convenience routine.
First, save a copy of the current rcParams dictionary so that we can easily reset
these changes. Now we can use the plt.rc function to change some of these settings.
Ex:
from matplotlib import cycler
colors = cycler('color', ['#EE6666', '#3388BB', '#9988DD', '#EECC55', '#88BB44',
'#FFBBBB'])
plt.rc('axes', facecolor='#E6E6E6', edgecolor='none', axisbelow=True, grid=True,
prop_cycle=colors)
plt.rc('grid', color='w', linestyle='solid')
plt.rc('lines', linewidth=2)
plt.hist(x)

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.

Synatx: with plt.style.context('stylename'):


make_a_plot()

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')

Three-Dimensional Points and Lines


The most basic three-dimensional plot is a line or scatter plot created from sets of
triples (x,y, z). We can create these using the ax.plot3D and ax.scatter3D functions. The call
signature for these is nearly identical.

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');

Three-Dimensional Contour Plots


Like two-dimensional ax.contour plots, ax.contour3D requires all the input data to be
in the form of two-dimensional regular grids, with the Z data evaluated at each point.

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)

Wireframes and Surface Plots


The two other types of three-dimensional plots that work on gridded data are
wireframes and surface plots. These take a grid of values and project it onto the specified three
dimensional surface.

Ex: Wireframe plot


fig = plt.figure()
ax = plt.axes(projection='3d')
ax.plot_wireframe(X, Y, Z, color='black')
ax.set_title('wireframe');
A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon.
Ex:
Surface plot
ax = plt.axes(projection='3d')
ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
cmap='viridis', edgecolor='none')
ax.set_title('surface')

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')
---

VISUALIZATION WITH SEABORN

Seaborn is an amazing visualization library for statistical graphics plotting. It is built


on the top of matplotlib library. It offers a range of built-in statistical functions that allows users
to easily perform complex statistical analysis with their visualizations. It provides a range of
default themes and color palettes, which you can easily customize to suit your preferences.

Seaborn Versus Matplotlib

Features Matplotlib Seaborn

It is utilized for making basic


Seaborn contains a number of
graphs. Datasets are visualised
patterns and plots for data
Functionality with the help of bargraphs,
visualization. It uses
histograms, scatter plots and so
fascinating themes.
on.

It uses comparatively simple


It uses comparatively complex and
Syntax syntax which is easier to learn
lengthy syntax.
and understand.

Dealing We can open and use multiple


Seaborn sets time for the
Multiple figures simultaneously. However
creation of each figure.
Figures they are closed distinctly.
Features Matplotlib Seaborn

Matplotlib is well connected with


Seaborn is more comfortable
Numpy and Pandas and acts as a
Visualization in handling Pandas data
graphics package for data
frames.
visualization in python.

Seaborn is much more


Matplotlib works efficiently with
Data Frames functional and organized than
data frames and arrays. It treats
and Arrays Matplotlib and treats the
figures and axes as objects
whole dataset as a single unit.

Seaborn Plot types


Seaborn provides a wide range of plot types that can be used for data visualization
and exploratory data analysis. Any visualization can fall into one of the three categories.

 Univariate – x only (contains only one axis of information)


 Bivariate – x and y (contains two axis of information)
 Trivariate – x, y, z (contains three axis of information)

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

You might also like