Coding/Python

Matplotlib 라이브러리 모음

폴밴 2022. 2. 22. 13:24
import matplotlib.pyplot as plt
%matplotlib inline

Basic Plot

import numpy as np
x = np.linspace(0,5,11)
y = x ** 2

plt.plot(x, y, 'red')
plt.xlabel('X Axis')
plt.ylabel('Y Axis')
plt.title('Title')
plt.show()

Subplot

plt.subplot(1,2,1)  # nrow, ncol, index(1~)
plt.plot(x, y, 'r')

plt.subplot(1,2,2)
plt.plot(y, x, 'b')

Object Oreinted Method

fig = plt.figure()

axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])  
# start point x, start point y, width, height (0~1)

axes.plot(x, y, 'b')
axes.set_xlabel('X Label')
axes.set_ylabel('Y Label')
axes.set_title('Title')

Add axes

fig = plt.figure()

axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes2 = fig.add_axes([0.2, 0.5, 0.3, 0.3]) # add axes in the bigger axes

axes1.plot(x, y, 'b')
axes2.plot(y, x, 'r')

Tight Layout

fig, axes = plt.subplots(1, 2)
axes  # numpy array

axes[0].plot(x,y)
axes[1].plot(y,x)

plt.tight_layout()  # prevent overlapping

Figsize

fig, axes = plt.subplots(figsize=(12,3))  # set plot size

axes.plot(x, y)

Savefig

fig.savefig('plot.png')  # export plot image

Legend

fig, axes = plt.subplots(1, 2)

axes[0].plot(x, x ** 2, label = 'x ** 2')  # set label of legend
axes[0].legend(loc = 1)  # show legend (default loc = 0, automatic)

axes[1].plot(x, x ** 3, label = 'x ** 3')
axes[1].legend(loc = 4)

Plot Style

fig, ax = plt.subplots()

# configuring linestyle, etc.
ax.plot(x, x + 1, color = 'red', lw = 1.5, ls = '--', marker = 'o', markersize = 10)

xlim, ylim (custom range)

fig, ax = plt.subplots()

ax.plot(x, x**3)
ax.set_ylim([10, 70])  # custom y domain
ax.set_xlim([2, 5])  # custom x domain

Various Plot Types

plt.scatter(x, x ** 3)

data = np.random.randint(1,1000,100)
plt.hist(data)

data = [np.random.normal(0, std, 100) for std in range(1,4)]  
# 100 normal random values

plt.boxplot(data, vert = True, patch_artist=True)