Matplotlib_Visualizations
Visual Analytics Matplotlib
Here we will show examples of how one could use Matplotlib for data visualization.
Copyright By Assignmentchef assignmentchef
Matplotlib is one of largest data visualization libraries for Python.
Install necessary libraries
#!pip install pandas
#!pip install numpy
#!pip install matplotlib
Import necessary libraries
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
%matplotlib inline
Draw a line plot, given a set of points
x = [0, 1, 2]
y = [3, 5, 4]
plt.plot(x, y)
[
Plot a histogram, given a 1D numpy array
arr = np.random.randint(0, 11, 50)
plt.hist(arr)
(array([6., 5., 3., 4., 8., 3., 3., 6., 6., 6.]),
array([ 0.,1.,2.,3.,4.,5.,6.,7.,8.,9., 10.]),
np.random.randint(low,high,size) generates random ingeters in the range of [low,high) (high is exclusive while low is inclusive). See https://docs.scipy.org/doc/numpy-1.15.1/reference/generated/numpy.random.randint.html for more information
Plot barplots given the center, value, and width of each bar.
centers = [0, 1, 2]
values = [25, 40, 35]
width = 0.8
plt.bar(centers, values, width=width)
Stacked bars
Plot stacked barplots, given the center, and values for each bar length.
centers = [0, 1, 2]
values_1 = [2, 3, 4]
values_2 = [8, 7, 6]
values_3 = [12, 10, 9]
plt.bar(centers, values_3)
plt.bar(centers, values_2)
plt.bar(centers, values_1)
Horizontal barplot
Plot horizontal barplots given the center, value, and height of each bar.
centers = [0, 1, 2]
values = [12, 16, 30]
height = 0.9
plt.barh(centers, values, height=height)
Stacked horisontal bars
Plot horizontal stacked barplots, given the center, and values for each bar length.
centers = [0, 1, 2]
values_1 = [2, 3, 4]
values_2 = [8, 7, 6]
values_3 = [12, 10, 9]
plt.barh(centers, values_3)
plt.barh(centers, values_2)
plt.barh(centers, values_1)
Plot a piechart, given the size of each size.
xs = [2, 5, 3] # 20% of pie, 50% of pie, and 30% of pie
plt.pie(xs)
plt.axis(equal)
(-1.1075815139419147,
1.1003610399515271,
-1.1133538550301745,
1.1082002194218503)
Stackplot
Plot a stockplot, given multiple lines. Each new line will be the summed value of itself + the lines below it.
x= np.arange(0, 10)
y1 = np.random.randint(1, 5, 10)
y2 = np.random.randint(2, 4, 10)
y3 = np.random.randint(1, 3, 10)
print (y1)
print (+)
print (y2)
print (+)
print (y3)
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3)
plt.show()
[2 3 3 3 3 1 1 4 4 1]
[3 2 3 3 2 2 3 3 3 3]
[2 2 1 2 1 1 2 1 2 2]
Plot multiple plots in the same figure using subplots>
size = (9, 5)
# Create rows x cols subplot of size size
fig, (ax1, ax2) = plt.subplots(rows, cols, figsize = size)
# Plot on ax1
ax1.plot(np.arange(10), np.random.rand(10))
# Plot on ax2
ax2.plot(np.arange(10), np.random.rand(10))
[
Include a legend with your plot.
loc : int or string or pair of floats, default: upper right
The location of the legend. Possible codes are:
=============== =============
Location String Location Code
=============== =============
best0
upper right 1
upper left2
lower left3
lower right 4
right 5
center left 6
center right7
lower center8
upper center9
center10
=============== =============
help(plt.legend)
Help on function legend in module matplotlib.pyplot:
legend(*args, **kwargs)
Place a legend on the axes.
Call signatures::
legend(labels)
legend(handles, labels)
The call signatures correspond to three different ways how to use
this method.
**1. Automatic detection of elements to be shown in the legend**
The elements to be added to the legend are automatically determined,
when you do not pass in any extra arguments.
In this case, the labels are taken from the artist. You can specify
them either at artist creation or by calling the
:meth:`~.Artist.set_label` method on the artist::
line, = ax.plot([1, 2, 3], label=Inline label)
ax.legend()
line, = ax.plot([1, 2, 3])
line.set_label(Label via method)
ax.legend()
Specific lines can be excluded from the automatic legend element
selection by defining a label starting with an underscore.
This is default for all artists, so calling `.Axes.legend` without
any arguments and without setting the labels manually will result in
no legend being drawn.
**2. Labeling existing plot elements**
To make a legend for lines which already exist on the axes
(via plot for instance), simply call this function with an iterable
of strings, one for each legend item. For example::
ax.plot([1, 2, 3])
ax.legend([A simple line])
Note: This way of using is discouraged, because the relation between
plot elements and labels is only implicit by their order and can
easily be mixed up.
**3. Explicitly defining the elements in the legend**
For full control of which artists have a legend entry, it is possible
to pass an iterable of legend artists followed by an iterable of
legend labels respectively::
legend((line1, line2, line3), (label1, label2, label3))
Parameters
–
handles : sequence of `.Artist`, optional
A list of Artists (lines, patches) to be added to the legend.
Use this together with *labels*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
The length of handles and labels should be the same in this
case. If they are not, they are truncated to the smaller length.
labels : list of str, optional
A list of labels to show next to the artists.
Use this together with *handles*, if you need full control on what
is shown in the legend and the automatic mechanism described above
is not sufficient.
`~matplotlib.legend.Legend`
Other Parameters
–
loc : str or pair of floats, default: :rc:`legend.loc` (best for axes, upper right for figures)
The location of the legend.
The strings
upper left, upper right, lower left, lower right
place the legend at the corresponding corner of the axes/figure.
The strings
upper center, lower center, center left, center right
place the legend at the center of the corresponding edge of the
axes/figure.
The string center places the legend at the center of the axes/figure.
The string best places the legend at the location, among the nine
locations defined so far, with the minimum overlap with other drawn
artists.This option can be quite slow for plots with large amounts of
data; your plotting speed may benefit from providing a specific location.
The location can also be a 2-tuple giving the coordinates of the lower-left
corner of the legend in axes coordinates (in which case *bbox_to_anchor*
will be ignored).
For back-compatibility, center right (but no other location) can also
be spelled right, and each string locations can also be given as a
numeric value:
=============== =============
Location String Location Code
=============== =============
best0
upper right 1
upper left2
lower left3
lower right 4
right 5
center left 6
center right7
lower center8
upper center9
center10
=============== =============
bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
Box that is used to position the legend in conjunction with *loc*.
Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
`figure.bbox` (if `.Figure.legend`).This argument allows arbitrary
placement of the legend.
Bbox coordinates are interpreted in the coordinate system given by
*bbox_transform*, with the default transform
Axes or Figure coordinates, depending on which legend is called.
If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
(x, y, width, height) that the legend is placed in.
To put the legend in the best location in the bottom right
quadrant of the axes (or figure)::
loc=best, bbox_to_anchor=(0.5, 0., 0.5, 0.5)
A 2-tuple (x, y) places the corner of the legend specified by *loc* at
x, y.For example, to put the legends upper right-hand corner in the
center of the axes (or figure) the following keywords can be used::
loc=upper right, bbox_to_anchor=(0.5, 0.5)
ncol : int, default: 1
The number of columns that the legend has.
prop : None or `matplotlib.font_manager.FontProperties` or dict
The font properties of the legend. If None (default), the current
:data:`matplotlib.rcParams` will be used.
fontsize : int or {xx-small, x-small, small, medium, large, x-large, xx-large}
The font size of the legend. If the value is numeric the size will be the
absolute font size in points. String values are relative to the current
default font size. This argument is only used if *prop* is not specified.
labelcolor : str or list
Sets the color of the text in the legend. Can be a valid color string
(for example, red), or a list of color strings. The labelcolor can
also be made to match the color of the line or marker using linecolor,
markerfacecolor (or mfc), or markeredgecolor (or mec).
numpoints : int, default: :rc:`legend.numpoints`
The number of marker points in the legend when creating a legend
entry for a `.Line2D` (line).
scatterpoints : int, default: :rc:`legend.scatterpoints`
The number of marker points in the legend when creating
a legend entry for a `.PathCollection` (scatter plot).
scatteryoffsets : iterable of floats, default: [0.375, 0.5, 0.3125]
The vertical offset (relative to the font size) for the markers
created for a scatter plot legend entry. 0.0 is at the base the
legend text, and 1.0 is at the top. To draw all markers at the
same height, set to [0.5].
markerscale : float, default: :rc:`legend.markerscale`
The relative size of legend markers compared with the originally
drawn ones.
markerfirst : bool, default: True
If *True*, legend marker is placed to the left of the legend label.
If *False*, legend marker is placed to the right of the legend label.
frameon : bool, default: :rc:`legend.frameon`
Whether the legend should be drawn on a patch (frame).
fancybox : bool, default: :rc:`legend.fancybox`
Whether round edges should be enabled around the `~.FancyBboxPatch` which
makes up the legends background.
shadow : bool, default: :rc:`legend.shadow`
Whether to draw a shadow behind the legend.
framealpha : float, default: :rc:`legend.framealpha`
The alpha transparency of the legends background.
If *shadow* is activated and *framealpha* is None, the default value is
facecolor : inherit or color, default: :rc:`legend.facecolor`
The legends background color.
If inherit, use :rc:`axes.facecolor`.
edgecolor : inherit or color, default: :rc:`legend.edgecolor`
The legends background patch edge color.
If inherit, use take :rc:`axes.edgecolor`.
mode : {expand, None}
If *mode* is set to expand the legend will be horizontally
expanded to fill the axes area (or *bbox_to_anchor* if defines
the legends size).
bbox_transform : None or `matplotlib.transforms.Transform`
The transform for the bounding box (*bbox_to_anchor*). For a value
of None (default) the Axes
:data:`~matplotlib.axes.Axes.transAxes` transform will be used.
title : str or None
The legends title. Default is no title (None).
title_fontsize : int or {xx-small, x-small, small, medium, large, x-large, xx-large}, default: :rc:`legend.title_fontsize`
The font size of the legends title.
borderpad : float, default: :rc:`legend.borderpad`
The fractional whitespace inside the legend border, in font-size units.
labelspacing : float, default: :rc:`legend.labelspacing`
The vertical space between the legend entries, in font-size units.
handlelength : float, default: :rc:`legend.handlelength`
The length of the legend handles, in font-size units.
handletextpad : float, default: :rc:`legend.handletextpad`
The pad between the legend handle and text, in font-size units.
borderaxespad : float, default: :rc:`legend.borderaxespad`
The pad between the axes and legend border, in font-size units.
columnspacing : float, default: :rc:`legend.columnspacing`
The spacing between columns, in font-size units.
handler_map : dict or None
The custom dictionary mapping instances or types to a legend
handler. This *handler_map* updates the default handler map
found at `matplotlib.legend.Legend.get_legend_handler_map`.
Some artists are not supported by this function.See
:doc:`/tutorials/intermediate/legend_guide` for details.
.. plot:: gallery/text_labels_and_annotations/legend.py
y1 = np.random.normal(0, 0.1, 100)
y2 = np.random.normal(0.5, 0.15, 100)
# subplot params
size = (9,5)
# create subplots
fig, (ax1, ax2) = plt.subplots(rows, cols, sharex=True, figsize=size)
# plot and label on first axes
ax1.plot(y1, label=y1)
ax1.plot(y2, label=y2)
ax1.legend(loc=3) # draw legend at loc=3
# plot and label on second axes
ax2.plot(y1)
ax2.plot(y2)
ax2.legend([y1,y2],loc=1)
Legend location
loc : int or string or pair of floats, default: upper right
The location of the legend. Possible codes are:
=============== =============
Location String Location Code
=============== =============
best0
upper right 1
upper left2
lower left3
lower right 4
right 5
center left 6
center right7
lower center8
upper center9
center10
=============== =============
Titles, ticks and ticklabels
# Create data
y1 = np.random.normal(-0.07, 0.05, 100)
y2 = [len(list(filter(lambda x: x < 0, y1))), len(list(filter(lambda x: x >= 0, y1)))]
# Create subplot
fig, axs = plt.subplots(1, 2, figsize=(12, 5.5))
# Plot data
axs[0].plot(y1)
axs[1].bar([0, 1], y2, 0.8, color=[r, g], alpha=0.5)
# Set titles for subplots
axs[0].set_title(Unordered sequence plot)
axs[1].set_title(Values count relative to zero)
# Set title for entire figure
fig.suptitle(Sequence of random values, size=14, weight=bold) # size weight set_title
# Remove xticks from the first plot
axs[0].set_xticks([])
# Add xticks for the second plot and rename them
axs[1].set_xticks([0, 1])
axs[1].set_xticklabels([below 0, greater or equal 0])
[Text(0, 0, below 0), Text(1, 0, greater or equal 0)]
Axvline, axhline, annotate
# create data
ys = np.random.normal(0, 0.1, 100)
# Plot data
plt.plot(ys)
# Get plot axes
ax = plt.gca()
# Remove x and y ticks
ax.set_xticks([])
ax.set_yticks([])
# Increase y axes range to -0.4 to 0.4
ax.set_ylim([-0.4, 0.4])
# Add title
ax.set_title(Horizontal and vertical lines example)
# Add horizontal line at minimum and maximum of ys
ax.axhline(min(ys), ls=, color=r, lw=0.5)
ax.axhline(max(ys), ls=, color=g, lw=0.5)
# Add text annotation of min and max values
ax.annotate(%0.4f % min(ys), xy=(0, min(ys)), ha=left, va=top)
ax.annotate(%0.4f % max(ys), xy=(100, max(ys)), ha=right, va=bottom)
# Add vertical line at first value and last value
ax.axvline(0, ls=:, color=grey, alpha=0.5)
ax.axvline(100, ls=:, color=magenta, alpha=0.5)
Combined Example
# Create data
positions = [0, 1, 2, 3]
vals = list(np.random.randint(10, 150, 4))
# Create bar plot
plt.bar(positions, vals, zorder=10, color=#bcbcac)
# Get axes
ax = plt.gca()
# Remove y ticks and set y axes title to group value
ax.set_yticks([])
ax.set_ylabel(group value)
# Set x ticks to positions and rename them to group A, B, C, etc.
ax.set_xticks(positions)
ax.set_xticklabels([group %s % l for l in ABCD])
# Annotate the value onto the respective bar plot
for i, v in enumerate(vals):
ax.annotate(v, xy=(i, v/2), ha=center, color=w, va=center, size=14, weight=bold, zorder=100)
# Set title
ax.set_title(Barplot demo)
# Draw horizontal line at mean of values
ax.axhline(np.mean(vals), ls=:, lw=1, alpha=0.5, color=k)
# Annotate the mean line with the mean value
ax.annotate(%0.1f % np.mean(vals), xy=(-0.5, np.mean(vals)), ha=right, va=bottom, zorder=1)
# extend the x axes range
ax.set_xlim(min(positions)-1, max(positions)+1)
# Save a figure to file
plt.savefig(demoplot.png)
Setting colors, linewidths, linetypes
There a lot of options within matplotlib for customizing colors, lindwidths and linetypes.
Some basic MATLAB style syntax can also be used.
MATLAB Style Syntax
x = np.linspace(0, 5, 11)
fig, ax = plt.subplots()
ax.plot(x, x**2, b.-) # blue line with dots
ax.plot(x, x**3, g) # green dashed line
[
Color with color parameter
We can also define colors by their names or RGB hex codes using the color argument.
We can optionally change the transparency using the alpha keyword.
fig, ax = plt.subplots()
ax.plot(x, x*1, color=blue, alpha=0.5)
CS: assignmentchef QQ: 1823890830 Email: [email protected]
Reviews
There are no reviews yet.