Skip to content

Latest commit

 

History

History
80 lines (66 loc) · 2.57 KB

File metadata and controls

80 lines (66 loc) · 2.57 KB

Matplotlib

Usage

import matplotlib.pyplot as plt

Automatic plotting

# Pyplot automatically figures out how to create and manage figures and axes
plt.plot(x, y)

OOP plotting

  1. Create a figure and axis
# Single axes
fig, ax = plt.subplots(figsize = (4,4))     # figsize argument is optional

# Multiple axes
fig, (ax1, ax2, ax3) = plt.subplots((1,3), figsize = (4,4))  # 1x3 grid

# 2D axes
fig, axs = plt.subplots(2,2, figsize=(5,5)) # 2x2 grid
  1. Plotting Plot on the ax object
ax.plot(x,y)
ax1.plot(x,x**2, label="quadratic")

# for 2D
axs[0,0].hist(x)
axs[0,1].scatter(x, y)
  1. Perform methods on axes
ax.set_xlabel('x_label')
ax.set_ylabel('y_label')
ax.set_title('title')
ax.legend()
  1. For precise layout
fig.tight_layout()
  1. Show plots
plt.show()

Different kinds of graphs

ax.bist(x)
ax.scatter(x,y)
ax.bar(x,y)
ax.hist2d(x, y)

Same x-axis

For e.g., two lines on the same graph

  1. Plot first line
fig, ax1 = plt.subplots()
ax1.plot(x, y)
  1. Make copy of axis
ax2 = ax1.twinx()   # share the same x-axiz
  1. Plot second line
ax2.plot(x2, y2)