A Summary of Common Code for Matplotlib

less than 1 minute read


Here I summarise some common code blocks when I use Matplotlib during research.

Basic knowledge

First, use fig, ax = plt.subplots(); ax.xxx to draw a figure and do not use plt.xxx

This figure gives explanations for each part when you use Matplotlib to draw a figure.

This figure gives names of each attribute to plot.

Scatter figure

import matplotlib
matplotlib.use('TkAgg') # this is for Mac environment
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns

x = np.arange(1,5,1)
y1 = np.arange(2,6,1)
y2 = np.arange(3,7,1)

fig, ax = plt.subplots()

ax.plot(x,y1, color='steelblue', linestyle='-') # draw a line
ax.plot(x,y2, color='steelblue', linestyle='-.')

a1_loc =ax.scatter([x[0],x[0]], [y1[0],y2[0]], marker='^', c='none', s=48, edgecolors='steelblue') # draw scatters
a2_loc =ax.scatter([x[1],x[1]], [y1[1],y2[1]], marker='v', c='steelblue', s=48, edgecolors='steelblue')
a3_loc =ax.scatter([x[2],x[2]], [y1[2],y2[2]], marker='s', c='none', s=48, edgecolors='steelblue')   
a4_loc =ax.scatter([x[3],x[3]], [y1[3],y2[3]], marker='o', c='steelblue', s=48, edgecolors='steelblue')

ax.text(1.5,2.6,r'$\bf{Line 1}$') # r'$$': Latex format
ax.text(1.5,3.7,r'$\bf{Line 2}$')

ax.legend([a1_loc,a2_loc,a3_loc,a4_loc],['a1','a2','a3','a4'], loc='upper left')

ax.set_title('This is a title', fontsize=12)
ax.set_xlabel('x label', fontsize=14)
ax.set_ylabel('y label', fontsize=14)


Leave a Comment