Learn Matplotlib Basic


In [ ]:
# show in notebook, and not block, # don't need call plt.show()
%matplotlib inline

In [ ]:
import numpy as np
import matplotlib.pylab as plt

# http://pandas.pydata.org/pandas-docs/version/0.13/visualization.html

# datetime timeseries display
# https://blog.csdn.net/fortware/article/details/51934814
# https://matplotlib.org/gallery/api/date.html

In [ ]:
# figure and show
fig = plt.figure(figsize=(2, 2))
ax = fig.add_subplot(111)

# set x/y scale range
ax.set_xlim([0,4])
ax.set_ylim([0,8])

# grid
ax.grid(True)

In [ ]:
# 设置子图之间的间距
plt.tight_layout(pad = 3, h_pad=0.5, w_pad=0.5)

# 为了防止Jupyter notebook有时候Double plot, 在plot函数的后面加分号;
plt.plot([1,2,3,4,5]);

In [ ]:
fig = plt.figure(figsize=(1, 1))
ax = fig.add_subplot(111)
ax.set_title('axis off')
ax.axis('off')
ax.plot([1,2,3,4,5])

In [ ]:
fig = plt.figure(figsize=(3, 3))
ax = fig.add_subplot(111)
# not my disired result
# ax.set_visible(Flase)

# set axis label
ax.set_xlabel('X')
ax.set_ylabel('Y')

ax.plot(np.random.randn(1000).cumsum(), label='line0')

# set axis scale and scale label
ax.set_xticks(range(0,1000,100))
ax.set_xticklabels(list('abcdefghij'))
# ax.set_xticklabels([])

In [ ]:
# get current axis
ax = plt.gca()
# y axis visible
ax.axes.get_yaxis().set_visible(False)
# x axis visible
ax.axes.get_xaxis().set_visible(False)

In [ ]:
# another set about axis and ticks
# plt.xticks([]) and plt.yticks([])
# plt.xlim([]) and plt.ylim([])
# plt.xlabel() and plt.ylabel()
# plt.axis('off')
# plt.tile()

In [ ]:
# hide the spines (轴,脊骨)
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(10, 2))
# clear the ticks on axis of x,y 
axes[0].set_xticks([])
axes[0].set_yticks([])

axes[1].xaxis.set_ticks_position('top')
axes[1].spines['bottom'].set_position(('data', 0.5))
axes[1].yaxis.set_ticks_position('right')
axes[1].spines['left'].set_position(('data', 0.5))

axes[2].spines['right'].set_color('none')
axes[2].spines['top'].set_color('none')
axes[2].spines['bottom'].set_position(('data', 0.5))

axes[2].set_yticklabels(list('abcdef'))
axes[2].set_xticks([])
# set the around size between subplots
plt.subplots_adjust(wspace=0.5, hspace=0)

In [ ]:
fig.set_figheight(10)
fig.set_figwidth(10)

在Cell中复用


In [ ]:
fig, ax = plt.subplots(1, 1, figsize=(4,4))
ax.scatter([1],[1])

In [ ]:
# 另一个cell
ax.scatter([2],[2])
fig