python logo


Tag: matplotlib

Matplotlib Histogram

Matplotlib can be used to create histograms. A histogram shows the frequency on the vertical axis and the horizontal axis is another dimension. Usually it has bins, where every bin has a minimum and maximum value. Each bin also has a frequency between x and infinite.

Related course

Matplotlib histogram example
Below we show the most minimal Matplotlib histogram:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.show()

Output:

minimal_hist Python histogram

A complete matplotlib python histogram
Many things can be added to a histogram such as a fit line, labels and so on. The code below creates a more advanced histogram.

#!/usr/bin/env python

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)

num_bins = 20
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)

# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')

# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()

Output:

python_histogram python_histogram

Download Examples

Matplotlib Line chart

A line chart can be created using the Matplotlib plot() function. While we can just plot a line, we are not limited to that. We can explicitly define the grid, the x and y axis scale and labels, title and display options.

Related course:

Line chart example
The example below will create a line chart.

from pylab import *
t = arange(0.0, 2.0, 0.01)
s = sin(2.5*pi*t)
plot(t, s)

xlabel('time (s)')
ylabel('voltage (mV)')
title('Sine Wave')
grid(True)
show()

Output:

python_matplotlib_linechart Python Matplotlib Line Chart

The lines:

from pylab import *

t = arange(0.0, 2.0, 0.01)
s = sin(2.5*pi*t)

simply define the data to be plotted.

from pylab import *

t = arange(0.0, 2.0, 0.01)
s = sin(2.5*pi*t)
plot(t, s)
show()

plots the chart.  The other statements are very straightforward: statements xlabel() sets the x-axis text, ylabel() sets the y-axis text, title() sets the chart title and grid(True) simply turns on the grid.

If you want to save the plot to the disk, call the statement:

savefig("line_chart.png")

Plot a custom Line Chart

If you want to plot using an array (list), you can execute this script:

from pylab import *

t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
plot(t, s)

xlabel('Item (s)')
ylabel('Value')
title('Python Line Chart: Plotting numbers')
grid(True)
show()

The statement:

t = arange(0.0, 20.0, 1)

defines start from 0, plot 20 items (length of our array) with steps of 1.

Output:

python_line_chart Python Line Chart from List

Multiple plots

If you want to plot multiple lines in one chart, simply call the plot() function multiple times. An example:

from pylab import *

t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
s2 = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
plot(t, s)
plot(t, s2)

xlabel('Item (s)')
ylabel('Value')
title('Python Line Chart: Plotting numbers')
grid(True)
show()

Output:

python_line_chart_multiple python line chart multiple

In case you want to plot them in different views in the same window you can use this:

import matplotlib.pyplot as plt
from pylab import *

t = arange(0.0, 20.0, 1)
s = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
s2 = [4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

plt.subplot(2, 1, 1)
plt.plot(t, s)
plt.ylabel('Value')
plt.title('First chart')
plt.grid(True)

plt.subplot(2, 1, 2)
plt.plot(t, s2)
plt.xlabel('Item (s)')
plt.ylabel('Value')
plt.title('Second chart')
plt.grid(True)
plt.show()

Output:

Python subplots Python subplots

The plt.subplot() statement is key here. The subplot() command specifies numrows, numcols and fignum.

Styling the plot
If you want thick lines or set the color, use:

plot(t, s, color="red", linewidth=2.5, linestyle="-")

 

Download Examples

Matplotlib Bar chart

Matplotlib may be used to create bar charts. You might like the Matplotlib gallery.

Matplotlib is a python library for visualizing data. You can use it to create bar charts in python. Installation of matplot is on pypi, so just use pip: pip install matplotlib

The course below is all about data visualization:

Related course:
Data Visualization with Matplotlib and Python

Bar chart code

A bar chart shows values as vertical bars, where the position of each bar indicates the value it represents. matplot aims to make it as easy as possible to turn data into Bar Charts.

A bar chart in matplotlib made from python code. The code below creates a bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.bar(y_pos, performance, align='center', alpha=0.5)
plt.xticks(y_pos, objects)
plt.ylabel('Usage')
plt.title('Programming language usage')

plt.show()

Output:

figure_barchart Python Bar Chart

Matplotlib charts can be horizontal, to create a horizontal bar chart:

import matplotlib.pyplot as plt; plt.rcdefaults()
import numpy as np
import matplotlib.pyplot as plt

objects = ('Python', 'C++', 'Java', 'Perl', 'Scala', 'Lisp')
y_pos = np.arange(len(objects))
performance = [10,8,6,4,2,1]

plt.barh(y_pos, performance, align='center', alpha=0.5)
plt.yticks(y_pos, objects)
plt.xlabel('Usage')
plt.title('Programming language usage')

plt.show()

Output:

Bar chart horizontal Bar chart horizontal

Bar chart comparison

You can compare two data series using this Matplotlib code:

import numpy as np
import matplotlib.pyplot as plt

# data to plot
n_groups = 4
means_frank = (90, 55, 40, 65)
means_guido = (85, 62, 54, 20)

# create plot
fig, ax = plt.subplots()
index = np.arange(n_groups)
bar_width = 0.35
opacity = 0.8

rects1 = plt.bar(index, means_frank, bar_width,
alpha=opacity,
color='b',
label='Frank')

rects2 = plt.bar(index + bar_width, means_guido, bar_width,
alpha=opacity,
color='g',
label='Guido')

plt.xlabel('Person')
plt.ylabel('Scores')
plt.title('Scores by person')
plt.xticks(index + bar_width, ('A', 'B', 'C', 'D'))
plt.legend()

plt.tight_layout()
plt.show()

Output:

barchart_python Python Bar Chart comparison

Stacked bar chart

The example below creates a stacked bar chart with Matplotlib. Stacked bar plots show diffrent groups together.

# load matplotlib
import matplotlib.pyplot as plt

# data set
x = ['A', 'B', 'C', 'D']
y1 = [100, 120, 110, 130]
y2 = [120, 125, 115, 125]

# plot stacked bar chart
plt.bar(x, y1, color='g')
plt.bar(x, y2, bottom=y1, color='y')
plt.show()

Output:

stacked bar chart

Download All Matplotlib Examples

 

Matplotlib legend

Matplotlib has native support for legends. Legends can be placed in various positions: A legend can be placed inside or outside the chart and the position can be moved.

The legend() method adds the legend to the plot. In this article we will show you some examples of legends using matplotlib.

Related course

Matplotlib legend inside
To place the legend inside, simply call legend():


import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()

matplot-legend Matplotlib legend inside

Matplotlib legend on bottom
To place the legend on the bottom, change the legend() call to:


ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),  shadow=True, ncol=2)

Take into account that we set the number of columns two ncol=2 and set a shadow.

The complete code would be:


import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),  shadow=True, ncol=2)
plt.show()


matplot-legend-bottom Legend placed on bottom

Matplotlib legend on top
To put the legend on top, change the bbox_to_anchor values:


ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00),  shadow=True, ncol=2)

Code:


import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.00), shadow=True, ncol=2)
plt.show()

matplotlib-legend-top Legend on top

Legend outside right
We can put the legend ouside by resizing the box and puting the legend relative to that:


chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)

Code:


import matplotlib.pyplot as plt
import numpy as np

y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend outside')
chartBox = ax.get_position()
ax.set_position([chartBox.x0, chartBox.y0, chartBox.width*0.6, chartBox.height])
ax.legend(loc='upper center', bbox_to_anchor=(1.45, 0.8), shadow=True, ncol=1)
plt.show()

matplotlib-legend-outside Matplotlib legend outside

 
Download Examples

Matplotlib save figure to image file

If you want to save matplotlib figures as individual files, you can do this with the savefig function. If you want to save figures in a single file, use the saveas function instead.

Matplotlib is a python plotting library which produces publication quality figures in a variety of hardcopy formats and interactive environments across platforms.

Related course
The course below is all about data visualization:
Data Visualization with Matplotlib and Python

Save figure

For those who didn’t know, matplotlib savefig creates a file of the current figure as a PNG (with transparency), and saves it to your filesystem.

So Matplotlib can save plots directly to a file using savefig(). In this article we won’t cover the installation of matplotlib, if you want to install it see the installation faq.

Savefig is useful when you need to save a figure for viewing outside of matplotlib, such as in another program, or when you want to use a vector graphics program (Inkscape, Illustrator, etc.) to modify it.

It’s also useful if you want to save a copy of a figure in the same directory as your matplotlib script.

The method can be used like this:


fig.savefig('plot.png')

It can make an image from the figure. It decides on the image format based on the extension. For example to save a jpg image named figure1. jpg. The figure image must have an extension of jpg, png, or pdf.

The savefig method

The savefig() method is part of the matplotlib.pyplot module. This saves the contents of your figure to an image file.

It must have the output file as the first argument. You can add the full path, relative path or no path. If you don’t define a path, it will save the image in the current working directory.

The most basic program you can do is just 5 lines of code:

import matplotlib.pyplot as plt
plt.plot([0, 1, 2, 3, 4], [0, 2, 4, 8, 16])
plt.xlabel('Months')
plt.ylabel('Movies watched')
plt.savefig('example.png')

This works for larger plots too:


# load matplotlib modules
import matplotlib
import matplotlib.pyplot as plt
import numpy as np

# data to plot
y = [2,4,6,8,10,12,14,16,18,20]
x = np.arange(10)

# create plot
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
plt.title('Legend inside')
ax.legend()

# save plot to file
fig.savefig('plot.png')

To change the format, simply change the extension like so:


fig.savefig('plot.pdf')

You can open your file with any external image program, because it’s just a regular image. If you use Linux, you can use the command below:


display plot.png

or open it in an image or pdf viewer if you saved it as pdf

matplotlib-plot-save A plot saved to a pdf

Additional savefig options

A number of new savefig options have been added to matplotlib. Backwards compatibility is maintained.
The options are:

savefig(filename, dpi=None, format='png', bbox_inches='tight', pad_inches=0.2, bbox=None, pad=None, dashes=None, loc='upper left', rot=0, vmax='I', vmin='I', hmax='I', hmin='I')

The output file name extension and format is controlled by the extension and format parameters; the above are defaults.

Useful parameters are:

  • filename the output file to save, if no path is included it will save it in the same directory as your program

  • transparent if you a transparent background set it to True

  • bbox_inches change the size of the white space around the image, in most cases tight is ideal

Save as PDF file

To save your matplotlib chart as a pdf, just change the file extension to .pdf


plt.savefig('line_plot.pdf')

The file will be saved in your working directory.

Save as SVG file

SVG is another vector-based graphics format, which lets you zoom in without losing quality. Not every program can open the svg image files.

To save as an SVG file, just change the extension to SVG


plt.savefig('line_plot.svg')

Save as JPEG file

If you save as jpeg file, you can include the quality parameter. This lets you save some disk space, but at the cost of image quality.


plt.savefig('line_plot.jpg', dpi=300, quality=80, optimize=True, progressive=True)

In general I recommend going with vector graphics formats like svg or pdf, because the quality is higher. If you don’t care about quality and just want to email the image or show it on a website, you could use png or jpeg.

Download Examples
 

Plot time with matplotlib

Matplotlib supports plots with time on the horizontal (x) axis. The data values will be put on the vertical (y) axis. In this article we’ll demonstrate that using a few examples.

It is required to use the Python datetime module, a standard module.

Related course

Plot time
You can plot time using a timestamp:


import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import datetime

# create data
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [datetime.datetime.now() + datetime.timedelta(hours=i) for i in range(len(y))]

# plot
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

matplotilb-time

If you want to change the interval use one of the lines below:


# minutes
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(len(y))]

Time plot from specific hour/minute

To start from a specific date, create a new timestamp using datetime.datetime(year, month, day, hour, minute).
Full example:


import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import datetime

# create data
customdate = datetime.datetime(2016, 1, 1, 13, 30)
y = [ 2,4,6,8,10,12,14,16,18,20 ]
x = [customdate + datetime.timedelta(hours=i) for i in range(len(y))]

# plot
plt.plot(x,y)
plt.gcf().autofmt_xdate()
plt.show()

Download Examples

Generate heatmap in Matplotlib

A heatmap can be created using Matplotlib and numpy.

Related courses
If you want to learn more on data visualization, this course is good:

Heatmap example


The histogram2d function can be used to generate a heatmap.

We create some random data arrays (x,y) to use in the program. We set bins to 64, the resulting heatmap will be 64x64. If you want another size change the number of bins.


import numpy as np
import numpy.random
import matplotlib.pyplot as plt

# Create data
x = np.random.randn(4096)
y = np.random.randn(4096)

# Create heatmap
heatmap, xedges, yedges = np.histogram2d(x, y, bins=(64,64))
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

# Plot heatmap
plt.clf()
plt.title('Pythonspot.com heatmap example')
plt.ylabel('y')
plt.xlabel('x')
plt.imshow(heatmap, extent=extent)
plt.show()

Result:

matplot-heatmap Matplotlib heatmap

The datapoints in this example are totally random and generated using np.random.randn()

 

PyQt5 Matplotlib

Matplotlib plots can be included in a PyQt5 application.
Several imports need to be added:


from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

We create a widget called PlotCanvas that includes the Matplotlib plot.

pyqt5-matplotlib Matplot plot in PyQt5 window

PyQt5 Matplotlib example
The example below embeds a matplotlib plot in a PyQt5 window.


import sys

from PyQt5.QtWidgets import QApplication, QMainWindow, QMenu, QVBoxLayout, QSizePolicy, QMessageBox, QWidget, QPushButton
from PyQt5.QtGui import QIcon


from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
import matplotlib.pyplot as plt

import random

class App(QMainWindow):

def __init__(self):
super().__init__()
self.left = 10
self.top = 10
self.title = 'PyQt5 matplotlib example - pythonspot.com'
self.width = 640
self.height = 400
self.initUI()

def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)

m = PlotCanvas(self, width=5, height=4)
m.move(0,0)

button = QPushButton('PyQt5 button', self)
button.setToolTip('This s an example button')
button.move(500,0)
button.resize(140,100)

self.show()


class PlotCanvas(FigureCanvas):

def __init__(self, parent=None, width=5, height=4, dpi=100):
fig = Figure(figsize=(width, height), dpi=dpi)
self.axes = fig.add_subplot(111)

FigureCanvas.__init__(self, fig)
self.setParent(parent)

FigureCanvas.setSizePolicy(self,
QSizePolicy.Expanding,
QSizePolicy.Expanding)
FigureCanvas.updateGeometry(self)
self.plot()


def plot(self):
data = [random.random() for i in range(25)]
ax = self.figure.add_subplot(111)
ax.plot(data, 'r-')
ax.set_title('PyQt Matplotlib Example')
self.draw()

if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())

Download PyQT5 Examples

3d scatterplot

Matplotlib can create 3d plots. Making a 3D scatterplot is very similar to creating a 2d, only some minor differences. On some occasions, a 3d scatter plot may be a better data visualization than a 2d plot. To create 3d plots, we need to import axes3d.

Related course:

Introduction
It is required to import axes3d:


from mpl_toolkits.mplot3d import axes3d

Give the data a z-axis and set the figure to 3d projection:


ax = fig.gca(projection='3d')

matplotlib-scatterplot-3d 3d scatter plot with Matplotlib

3d scatterplot


Complete 3d scatterplot example below:


import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d

# Create data
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N),0.4+0.1*np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N),0.1*np.random.rand(N))
g3 = (0.3*np.random.rand(N),0.3*np.random.rand(N),0.3*np.random.rand(N))

data = (g1, g2, g3)
colors = ("red", "green", "blue")
groups = ("coffee", "tea", "water")

# Create plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, axisbg="1.0")
ax = fig.gca(projection='3d')

for data, color, group in zip(data, colors, groups):
x, y, z = data
ax.scatter(x, y, z, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

plt.title('Matplot 3d scatter plot')
plt.legend(loc=2)
plt.show()

The plot is created using several steps:


  • vector creation (g1,g2,g3)

  • list creation (groups)

  • plotting


The final plot is shown with plt.show()

Matplot Matrix Correlation

A correlation diagram can be created using Matplotlib. Matplotlib is the most used plotting library for Python. It can be included in all the graphical toolkits that are available for Python.

Related courses

  • Data Visualization with Matplotlib and Python


  • Matrix definition
    To start we define a 2x2 matrix and a list called groups. The matrix is defined inside the brackets (double [[ and ]] if written on a single line).


    m = [
    [1,0,2,0,0],
    [1,1,1,2,0],
    [0,4,1,0,0],
    [0,4,4,1,2],
    [1,3,0,0,1],
    ]

    groups = ['Blues','Jazz','Rock','House','Dance']

    Visual:

    matrixCorrelation Correlation using Matplotlib

    Matrix correlation


    The code below generates a Matrix correlation diagram using Matplotlib.


    import matplotlib.pyplot as plt
    import numpy as np

    m = [
    [1,0,2,0,0],
    [1,1,1,2,0],
    [0,4,1,0,0],
    [0,4,4,1,2],
    [1,3,0,0,1],
    ]

    plt.matshow(m)

    groups = ['Blues','Jazz','Rock','House','Dance']

    x_pos = np.arange(len(groups))
    plt.xticks(x_pos,groups)

    y_pos = np.arange(len(groups))
    plt.yticks(y_pos,groups)

    plt.show()

    Initially we define the matrix (m) and the list (groups).
    We set the length to be equal to the length of the groups. On the x axis and y axis we set the group names.