python logo


Category: plotting

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

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

 

pie chart python

Matplotlib is a versatile library in Python that supports the creation of a wide variety of charts, including pie charts. Check out the Matplotlib gallery to explore more chart types.

Related course: Data Visualization with Matplotlib and Python

Crafting a Pie Chart with Matplotlib

To begin with, ensure you’ve imported the required module using: import matplotlib.pyplot as plt. Once done, the plt.pie() method is readily available for creating your pie chart.

Here’s a simple example that demonstrates how to generate a pie chart:

import matplotlib.pyplot as plt

# Defining data for the chart
labels = 'Python', 'C++', 'Ruby', 'Java'
sizes = [215, 130, 245, 210]
colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue']
explode = (0.1, 0, 0, 0) # explode 1st slice

# Plotting the chart
plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=140)
plt.axis('equal')
plt.show()

With the above code, the result is a visually pleasing pie chart.

pie chart python

Matplotlib allows for extensive customization. You can determine slice sizes, which segments should stand out from the center (explode), their respective labels, and even their colors.

plt.pie(sizes, explode=explode, labels=labels, colors=colors, ...)

Enhancing Your Pie Chart with a Legend

To make your pie chart even more informative, consider adding a legend using the plt.legend() function. This overlays a legend on your chart, providing clarity.

import matplotlib.pyplot as plt

labels = ['Cookies', 'Jellybean', 'Milkshake', 'Cheesecake']
sizes = [38.4, 40.6, 20.7, 10.3]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
patches, texts = plt.pie(sizes, colors=colors, shadow=True, startangle=90)
plt.legend(patches, labels, loc="best")
plt.axis('equal')
plt.tight_layout()
plt.show()

This code renders a pie chart that’s enriched with a legend.

python pie chart

Always remember, after setting up your plot, call the method .show() to ensure it gets displayed.

plt.show()

For more examples and downloadable code, click here.


Navigation: [

Matplotlib legend

matplotlib save figure

matplotlib update plot

Updating a matplotlib plot is straightforward. Create the data, the plot and update in a loop.
Setting interactive mode on is essential: plt.ion(). This controls if the figure is redrawn every draw() command. If it is False (the default), then the figure does not update itself.

Related course:

Update plot example

Copy the code below to test an interactive plot.


import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)

plt.ion()
fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

for phase in np.linspace(0, 10*np.pi, 100):
line1.set_ydata(np.sin(0.5 * x + phase))
fig.canvas.draw()

matplotlib-update Capture of a frame of the program above

Explanation
We create the data to plot using:


x = np.linspace(0, 10*np.pi, 100)
y = np.sin(x)

Turn on interacive mode using:


plt.ion()

Configure the plot (the ‘b-‘ indicates a blue line):


fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'b-')

And finally update in a loop:


for phase in np.linspace(0, 10*np.pi, 100):
line1.set_ydata(np.sin(0.5 * x + phase))
fig.canvas.draw()

Download Examples
 

matplotlib time axis

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

matplotlib heatmap

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

 

python scatter plot

Matplot has a built-in function to create scatterplots called scatter(). A scatter plot is a type of plot that shows the data as a collection of points. The position of a point depends on its two-dimensional value, where each value is a position on either the horizontal or vertical dimension.

Related course

Scatterplot example
Example:


import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 500
x = np.random.rand(N)
y = np.random.rand(N)
colors = (0,0,0)
area = np.pi*3

# Plot
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.title('Scatter plot pythonspot.com')
plt.xlabel('x')
plt.ylabel('y')
plt.show()

matplotlib-scatter-plot Scatter plot created with Matplotlib

Scatter plot with groups
Data can be classified in several groups. The code below demonstrates that:


import numpy as np
import matplotlib.pyplot as plt

# Create data
N = 60
g1 = (0.6 + 0.6 * np.random.rand(N), np.random.rand(N))
g2 = (0.4+0.3 * np.random.rand(N), 0.5*np.random.rand(N))
g3 = (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")

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

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

Related course

matplotlib-scatter Scatter plot with classes

3d scatter plot python

subplot python

python plot matrix