An Introduction to Python Matplotlib with 40 Basic Examples
By: Christopher Tao
Tags: Data Visualization, Data Science, Matplotlib, Python, Data Analysis

Matplotlib is one of the most popular libraries in Python. Although there are other libraries such as Seaborn and Plotly which are more advanced in terms of various styles and easy-to-use, Matplotlib is classic and has existed for a much longer time. Therefore, it supports more types of graphs and has more possibilities that could satisfy any requirement.

It is essential for a “Python-based” Data Scientist/Analyst to master at least three libraries:

Pandas — Data I/O and Transformation

Numpy — Data Computing

Matplotlib — Data Visualisation

Once you have nailed Matplotlib, other data visualisation libraries such as Plotly will also be much simpler to learn.

Let’s start the examples!

1. Import the library

import matplotlib.pyplot as plt

In general, it is very common to import matplotlib with the alias plt . Of course, you can define whatever alias you want, but you will find that almost everyone use plt . So, it will be easier if you use the same one to improve your code readability.

2. Draw a sin function curve in a range

x = np.linspace(0, 10, 30)

plt.plot(x, np.sin(x))

plt.show()

3. Emphasize the points on the curve

plt.plot(x, np.sin(x), '-o')

plt.show()

Note: the dash — tells the plot to display the line, while the o tells the plot to display the scatter.

4. Draw the sin function using a dashed line

plt.plot(x, np.sin(x), '--')

plt.show()

5. Configure the range of the y-axis to (-2, 2)

plt.plot(x, np.sin(x))

plt.ylim(-2, 2)

plt.show()

6. Set labels of the x-axis and y-axis

plt.plot(x, np.sin(x))

plt.xlabel('variable')

plt.ylabel('value')

plt.show()

7. Set title of the chart

plt.plot(x, np.sin(x))

plt.title('sin function')

plt.show()

8. Show grids

plt.plot(x, np.sin(x))

plt.grid()

plt.show()

9. Draw a horizontal line on y=0.5

plt.plot(x, np.sin(x))

plt.axhline(y=0.5, ls='--', c='r')

plt.show()

Note: ls='--' tells plt to draw a dashed line, and c='r' means to use red colour.

10. Draw reference spaces on the plot

plt.plot(x, np.sin(x))

plt.axvspan(xmin=np.pi, xmax=np.pi*2, facecolor='r', alpha=0.2)

plt.axhspan(ymin=-1, ymax=0, facecolor='b', alpha=0.2)

plt.show()

11. Text-annotate plot at a certain coordinate

plt.plot(x, np.sin(x))

plt.text(np.pi, 0, 'y=0', weight='bold', c='r')

plt.show()

12. More complicated annotation using an arrow to point out the highest point

plt.plot(x, np.sin(x))

plt.annotate(

'1st-highest', xy=(np.pi/2, 1), xytext=(np.pi/2 + 1, 1), c='r',

arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r')

)

plt.annotate(

'2nd-highest', xy=(np.pi*2.5, 1), xytext=(np.pi*2.5 + 1, 1), c='r',

arrowprops=dict(arrowstyle='->', connectionstyle='arc3', color='r')

)

plt.xlim(-0.2, 12)

plt.show()

13. Draw the sin function in a scatter plot

plt.scatter(x, np.sin(x))

plt.show()

14. Show multiple lines in a single plot with legends

plt.plot(x, np.sin(x), label='sin')

plt.plot(x, np.cos(x), label='cos')

plt.legend()

plt.show()

15. Adjust legends position and disable frame

plt.plot(x, np.sin(x), label='sin')

plt.plot(x, np.cos(x), label='cos')

plt.legend(loc='upper right', frameon=False)

plt.show()

16. Display legend in columns on the central bottom position

plt.plot(x, np.sin(x), label='sin')

plt.plot(x, np.cos(x), label='cos')

plt.ylim(-1.5, 1.2)

plt.legend(loc='lower center', frameon=False, ncol=2)

plt.show()

17. Show partial legends only

plt.plot(x, np.sin(x))

plt.plot(x, np.cos(x))

plt.legend(['sin'])

plt.show()

18. Display legends using different styles for the plots

lines = []

line_styles = ['-', '-.', '--', ':']

line_colors = ['red', 'blue', 'green', 'black'] x = np.linspace(0, 10, 1000) for i in range(4):

line, = plt.plot(

x,

np.sin(x - i * np.pi / 2),

line_styles[i],

color=line_colors[i]

)

lines.append(line) legend1 = plt.legend(lines[:2], ['part A', 'part B'], loc='upper right')

legend2 = plt.legend(lines[2:], ['part C', 'part B'], loc='lower right')

plt.gca().add_artist(legend1)

plt.gca().add_artist(legend2) plt.show()

Note: we need to use the gca() method will get all the axes on the current figure, because the method add_artist() needs to be used on axes.

19. Show 2-D regular raster

x = np.linspace(0, 10, 1000)

matrix = np.sin(x) * np.cos(x[:, np.newaxis]) plt.imshow(matrix)

plt.show()

20. Show 2-D regular raster with customised colour

plt.imshow(matrix, cmap='hot')

plt.show()

21. Show 2-D regular raster with discrete colours and a scale bar in a defined range

plt.imshow(matrix, cmap=plt.cm.get_cmap('hot', 10))

plt.colorbar()

plt.clim(-1, 1)

plt.show()

22. Visualising a set dataset with 4 dimensions

x = np.random.randn(100)

y = np.random.randn(100)

colors = np.random.rand(100)

sizes = 100 * np.random.rand(100) plt.scatter(x, y, c=colors, s=sizes, alpha=0.5, cmap='viridis')

plt.colorbar()

plt.show()

Note: the 4 dimensions are demonstrated by the x-axis, y-axis, point size and colour scale.

23. Draw a scatter plot with errors on the y-axis (e.g. 0.8)

x = np.linspace(0, 10, 50)

yerr = 0.8

y = np.sin(x) + yerr * np.random.randn(50) plt.errorbar(x, y, yerr=yerr, fmt='.k')

plt.show()

24. Draw a bar chart

x = [1,2,3,4,5,6,7,8,9,10]

y = np.random.randint(10, size=10)

label = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'] plt.bar(x, y, tick_label=label)

plt.show()

25. Draw a horizontal bar chart

plt.barh(x, y, tick_label=label)

plt.show()

26. Draw a histogram with random numbers

rd_nums = np.random.randn(1000)

plt.hist(rd_nums)

plt.show()

27. Specify the number of bins of a histogram

plt.hist(rd_nums, bins=50)

plt.show()

28. Draw 3 histograms in the same plot with alpha

h1 = np.random.normal(0, 0.8, 1000)

h2 = np.random.normal(-3, 1.2, 1000)

h3 = np.random.normal(4, 0.5, 1000) kwargs = dict(bins=40, alpha=0.5) plt.hist(h1, **kwargs)

plt.hist(h2, **kwargs)

plt.hist(h3, **kwargs)

plt.show()

29. Draw a 2-D histogram (heatmap)

x, y = np.random.multivariate_normal([0,0], [[1,1],[1,2]], 10000).T plt.hist2d(x, y, bins=30)

plt.show()

30. Draw a 2-D histogram in a 30x30 hexagon grids (a bit fancy)

plt.hexbin(x, y, gridsize=30)

plt.show()

31. Show a plot embedded in a parent plot

ax1 = plt.axes()

ax2 = plt.axes([0.5, 0.5, 0.2, 0.2])

plt.show()

32. Show 2 different lines in subplots

fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.5, 0.8, 0.4], ylim=(-2, 2))

ax2 = fig.add_axes([0.1, 0.0, 0.8, 0.4], ylim=(-2, 2)) x = np.linspace(0, 10)

ax1.plot(np.sin(x))

ax2.plot(np.cos(x)) plt.show()

33. Show more subplots with equal sizes

for i in range(1, 5):

plt.subplot(2, 2, i)

plt.text(0.5, 0.5, str((2, 2, i)), fontsize=15, ha='center') plt.show()

34. Create grid subplots sharing x-axis and y-axis

plt.subplots(2, 2, sharex='all', sharey='all')

plt.show()

35. Customise each subplot based on indices

_,axes = plt.subplots(2, 2, sharex='all', sharey='all') for i in range(2):

for j in range(2):

axes[i][j].text(0.5, 0.5, str((i,j)), fontsize=15, ha='center') plt.show()

36. Subplots in a grid with different sizes

grid = plt.GridSpec(2, 3, wspace=0.4, hspace=0.3)

plt.subplot(grid[0,0])

plt.subplot(grid[0,1:])

plt.subplot(grid[1,:2])

plt.subplot(grid[1,2])

plt.show()

37. Plot 2-D dataset with separated x and y-axis frequency histogram

# Generate normal distributed sample points in 2-D

x, y = np.random.multivariate_normal([0, 0], [[1, 1], [1, 2]], 3000).T # Define subplot styles

fig = plt.figure(figsize=(10, 10))

grid = plt.GridSpec(4, 4, hspace=0.2, wspace=0.2)

ax = fig.add_subplot(grid[:-1, 1:])

ax_x = fig.add_subplot(grid[-1, 1:])

ax_y = fig.add_subplot(grid[:-1, 0]) # Plot the data to subplots

ax.scatter(x, y, s=3, alpha=0.5)

ax_x.hist(x, 40, orientation='vertical')

ax_y.hist(y, 40, orientation='horizontal')

ax_x.invert_yaxis()

ax_y.invert_xaxis() plt.show()

38. Create a 3-D canvas

from mpl_toolkits import mplot3d ax = plt.axes(projection='3d')

Note: another toolkit mplot3d needs to be involved to plot in 3-D space

39. Draw a 3-D twisting curve

ax = plt.axes(projection='3d')

z = np.linspace(0, 50, 3000)

x = np.sin(z)

y = np.cos(z)

ax.plot3D(x, y, z)

plt.show()

40. Draw a 3-D scatter plot

ax = plt.axes(projection='3d')

z = np.random.random(100)

x = np.sin(z) + np.random.randn(100)

y = np.cos(z) + np.random.randn(100)

ax.scatter3D(x, y, z)

That finalises the introduction. I will keep exploring more python libraries in future stories.

Resources

Matplotlib: https://matplotlib.org/