TOC

Matplotlib 基础

简单例子

from matplotlib import pyplot as plt
import numpy as np
plt.plot(np.arange(10))

Figure / Subplot

fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)

# 折线图
plt.plot(np.range.randn(50).cumsum(), 'k--')

# 直方图
# k 灰, r 红
ax1.hist(np.random.randn(100), bins=20, color='k', alpha=0.3)
fig

# 散点图
ax2.scatter(np.arange(30), np.arange(30) + 3 * np.random.randn(30))
fig

fig, axes = plt.subplots(2, 2, sharex=True, sharey=True)
for i in range(2):
    for j in range(2):
        axes[i, j].hist(np.random.randn(500), bins=50, color='r', alpha=0.5)
plt.subplots_adjust(wspace=0, hspace=0)
ax.plot(x, y, 'g--')
ax.plot(x, y, linestyle='--', color='g')
data = np.random.randn(30).cumsum()
data
plt.plot(data, 'k--', label='Default')
plt.plot(data, 'k-', drawstyle='steps-post', label='steps-post')
# 'k--', 'k.'

标题

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
data = np.random.randn(1000).cumsum()
print(data)
ax.plot(data)

ax.set_title('abc')
ax.set_xlabel('stages')
ticks = ax.set_xticks([0, 250, 500, 750, 1000])
labels = ax.set_xticklabels(['a', 'b', 'c', 'd', 'e'], rotation=30, fontsize='small')
fig

图例

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ax.plot(np.random.randn(100).cumsum(), 'k', label='one')
ax.plot(np.random.randn(100).cumsum(), 'g', label='two')
ax.plot(np.random.randn(100).cumsum(), 'r', label='three')
ax.plot(np.random.randn(100).cumsum(), 'b', label='four')
ax.legend(loc='best')  # 自动选择最佳位置放图例