Matplotlib

2021-01-19

  • 1 Basics
    • 1.1 Figure Manipulation
      • 1.1.1 clear figure
    • 1.2 Line style
      • 1.2.1 More dash styles
    • 1.3 Axis style
      • 1.3.1 Scientific notation of tick label
  • 2 Advanced
    • 2.1 Axis style
      • 2.1.1 Different scales of the twin axis
      • 2.1.2 Align the gridlines of the twin y-axis
    • 2.2 3D style
      • 2.2.1 With equal aspect ratio z-axis is not equal to x- and y-
    • 2.3 Figure Manipulation
      • 2.3.1 Embed Figure in Figure

1 Basics

1.1 Figure Manipulation

1.1.1 clear figure

plt.cla() clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.

plt.clf() clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.

plt.close() closes a window, which will be the current window, if not specified otherwise.

fig.clf() clears the entire figure. This call is equivalent to plt.clf() only if fig is the current figure.

fig.clear() is a synonym for fig.clf().

1.2 Line style

1.2.1 More dash styles

plt.plot(x, y, dashes=[10, 5, 20, 5], linewidth=2, color='black')

1.3 Axis style

1.3.1 Scientific notation of tick label

plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))

This applies scientific notation (i.e. 1 x 10^4) to your x-axis tick label.

2 Advanced

2.1 Axis style

2.1.1 Different scales of the twin axis

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
import matplotlib.pyplot as plt

# Create some mock data
t = np.arange(0.01, 10.0, 0.01)
data1 = np.exp(t)
data2 = np.sin(2 * np.pi * t)

fig, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('time (s)')
ax1.set_ylabel('exp', color=color)
ax1.plot(t, data1, color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
ax2.plot(t, data2, color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  # otherwise the right y-label is slightly clipped
plt.show()

2.1.2 Align the gridlines of the twin y-axis

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')

# ADD THIS LINE
ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))

plt.show()

2.2 3D style

2.2.1 With equal aspect ratio z-axis is not equal to x- and y-

The matplotlib does not yet set correctly equal axis in 3D. The solution is to create a bounding box.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect('equal')

X = np.random.rand(100)*10+5
Y = np.random.rand(100)*5+2.5
Z = np.random.rand(100)*50+25

scat = ax.scatter(X, Y, Z)

max_range = np.array([X.max()-X.min(), Y.max()-Y.min(), Z.max()-Z.min()]).max() / 2.0

mid_x = (X.max()+X.min()) * 0.5
mid_y = (Y.max()+Y.min()) * 0.5
mid_z = (Z.max()+Z.min()) * 0.5
ax.set_xlim(mid_x - max_range, mid_x + max_range)
ax.set_ylim(mid_y - max_range, mid_y + max_range)
ax.set_zlim(mid_z - max_range, mid_z + max_range)

plt.show()

2.3 Figure Manipulation

2.3.1 Embed Figure in Figure

import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
# These are in unitless percentages of the figure size. (0,0 is bottom left)
left, bottom, width, height = [0.25, 0.6, 0.2, 0.2]
ax2 = fig.add_axes([left, bottom, width, height])
ax1.plot(range(10), color='red')
ax2.plot(range(6)[::-1], color='green')
plt.show()
.
Created on 2021-01-19 with pandoc