matplotlib手册(8) - 绘图知识点杂记

matplotlib手册(8)

这里会整理些matplotlib绘图的小知识点,可能比较杂。

1. subplot

前面,我们有简单的说过subplot,通过他,我们可以在一个figure上,分割多个区域分别去绘图,
这里说一个最常用的方法

1
2
3
4
matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)
Create a figure and a set of subplots
This utility wrapper makes it convenient to create common layouts of subplots, including the enclosing figure object, in a single call

1
2
3
4
5
6
7
8
9
10
import numpy as np
import matplotlib.pyplot as plt
#初始化2行2列的figure
f,axes = plt.subplots(2,2)
#这样通过下标可以快速的获取axes
axes[0,1].hist(np.random.randn(100),bins=20)
plt.show()

我们还可以设置,是否共享x轴y轴

调整subplot周围的间距

1
2
3
4
5
6
7
8
9
10
11
12
13
matplotlib.pyplot.subplots_adjust(*args, **kwargs)
subplots_adjust(left=None, bottom=None, right=None, top=None,
wspace=None, hspace=None)
left = 0.125 # the left side of the subplots of the figure
right = 0.9 # the right side of the subplots of the figure
bottom = 0.1 # the bottom of the subplots of the figure
top = 0.9 # the top of the subplots of the figure
wspace = 0.2 # the amount of width reserved for blank space between subplots,
# expressed as a fraction of the average axis width
hspace = 0.2 # the amount of height reserved for white space between subplots,
# expressed as a fraction of the average axis height

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import numpy as np
import matplotlib.pyplot as plt
#初始化2行2列的figure
f,axes = plt.subplots(2,2)
data=np.random.randn(10).cumsum()
axes[0,0].plot(data,marker='o')
axes[0,0].set_title('default')
#drawstyle
[‘default’ | ‘steps’ | ‘steps-pre’ | ‘steps-mid’ | ‘steps-post’]
axes[0,1].plot(data,drawstyle='steps-pre',marker='o')
axes[0,1].set_title('steps-pre')
axes[1,0].plot(data,drawstyle='steps-mid',marker='o')
axes[1,0].set_title('steps-mid')
axes[1,1].plot(data,drawstyle='steps-post',marker='o')
axes[1,1].set_title('steps-post')
#plt.subplots_adjust(hspace=0)
plt.show()

我们这里,可以设置轴要显示的刻度
比如,上面显示的是0,2,4,6,8

1
2
3
4
#设置显示的x轴的值
axes[0,0].set_xticks([0,5,10])
#将上面的值,替换为标签
axes[0,0].set_xticklabels(['one','two','three'])

好了,这里先补充这些,后面有的话继续,下一篇整理下pandas中绘图的方法

于贵洋 wechat
要教我弹吉他嘛!