matplotlibAPI入门
API入门
Figure和subplot
matplotlib的图像都位于FIgure对象中,不能通过空Figure绘图,必须用add_subplot()创建一个或多个subplot才行
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1) #图像应该是2X2的,且当前选中的是4个中的第一个(编号从1开始)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
#此时在最后一个用过的subplot上进行绘制
plt.plot(randn(50).cumsum(),'k--') #'k--'是线型选项,表示画黑色虚线图
#直接调用AxesSubplot对象的实例方法画图
_ = ax1.hist(randn(100),bins=20,color='k',alpha=0.3)
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))
fig,axes = plt.subplots(2,3) #axes为数组
调整subplot周围的间距:
subplots_adjust(left=None,botton=None,right=None,top=None,wspace=None,hspace=None)
fig,axes = plt.subplots(2,2,sharex=True,sharey=True)
for i in range(2):
for j in range(2):
axes[i,j].hist(randn(500),bins=50,color='k',alpha=0.5)
plt.subplots_adjust(wspace=0,hspace=0) #无间距
颜色和线型
ax.plot(x,y,'g--')
ax.plot(x,y,linestyle='--',color='g') #更明确
刻度、标签和图例
图表范围
ax.set_xlim()
ax.get_xlim()
图表刻度、标签
ax.set_xticks() #修改x轴刻度
ax.set_xticklabels() #修改x轴刻度标签
ax.set_xlabel #给x轴设置一个名称
y轴的修改方式与此类似
ticks = ax.set_xticks([0,250,500,750,1000]) #修改x轴刻度
#rotation 旋转度数
labels = ax.set_xticklabels(['one','two','three','four','five'],rotation=30,fontsize='small') #修改x轴刻度标签
ax.set_xlabel('Stages')
添加图例:
可以调用 ax.legend() 或 plt.legend() 来自动创建图例
fig = plt.figure();ax = fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum(),'k',label='one')
ax.plot(randn(1000).cumsum(),'k--',label='two')
ax.plot(randn(1000).cumsum(),'k.',label='three')
ax.legend(loc='best') #‘best’选择最不碍事的位置
注解以及在Subplot上绘图
可以通过text,arrow,annotate等函数进行添加注解
#text可以将文本绘制在图表的指定坐标(x,y),还可自定义格式
ax.text(50,10,'hello world!',family='monospace',fontsize=10)
图形的绘制
matplotlib有一些表示常见图形的对象,这些对象被称为块(patch)。其中有些可以在matplotlib.pyplot中找到(如Rectangle和Circle),但完整集合位于matplotlib.patches
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
rect = plt.Rectangle((0.2,0.75),0.4,0.15,color='k',alpha=0.3)
circle = plt.Circle((0.7,0.2),0.15,color='b',alpha=0.3)
pgon = plt.Polygon([[0.15,0.15],[0.35,0.4],[0.2,0.6]],color='g',alpha=0.5)
ax.add_patch(rect)
ax.add_patch(circle)
ax.add_patch(pgon)
将图表保存到文件
plt.savefig()可以将当前图表保存到文件,不仅可以写入磁盘,也可以写入任何文件型的对象,比如StringIO
plt.savefig('out/three_patch.svg')
plt.savefig('figpath',dpi=400,bbox_inches='tight') #dpi(控制“每英寸点数”分辨率)和bbox_inches(可以减除当前图表周围的空白部分)
from io import StringIO
buffer = StringIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()
参数 | 说明 |
---|---|
fname | 含有文件路径的字符串或Python的文件型对象。图像格式有文件扩展名推断得出 |
dpi | 图像分辨率,默认为100 |
facecolor、edgecolor | 图像的背景色,默认为’w’(白色) |
format | 显示设置文件格式 |
bbox_inches | 图标需要保存的部分。如果设置为’tight’,则将尝试剪除图标周围的空白部分 |
matplotlib配置
#matplotlib 配置
plt.rc('figure',figsize=(5,5))
#传入字典,多个参数同时改变
font_options = {
'family':'monospace',
'weight':'bold',
'size':'5'}
plt.rc('font',**font_options)
pandas中的绘图函数
线型图
from pandas import Series,DataFrame
s = Series(np.random.randn(10).cumsum(),index=np.arange(0,100,10))
s.plot()
df = DataFrame(np.random.randn(10,4).cumsum(0),
columns=['A','B','C','D'],
index=np.arange(0,100,10))
df.plot()
Series.plot方法
参数 | 说明 |
---|---|
label | 用于图例的标签 |
ax | subplot对象,若未设置则使用当前subplot对象 |
style | 传给matplotlib的风格字符串,如’ko–’ |
alpha | 图表的填充不透明度(0~1) |
kind | {‘line’,‘bar’,‘barh’, ‘kde’} |
logy | 在y轴上使用对数标尺 |
use_index | 将对象的索引用作刻度标签 |
rot | 旋转刻度标签(0 ~ 360) |
xsticks | 用作X轴刻度的值 |
ysticks | 用作Y轴刻度的值 |
xlim | X轴的界限 |
ylim | Y轴的界限 |
grid | 显示轴网格线(默认打开) |
专用于DataFrame的plot的参数
参数 | 说明 |
---|---|
subplots | 将各个DataFrame列绘制到单独的subplot中 |
sharex | 如果subplots=True,则共用同一个X轴,包括刻度和界限 |
sharey | 如果subplots=True,则共用同一个Y轴 |
figsize | 表示图像大小的元组 |
title | 图像标题的字符串 |
legend | 图例,默认为True |
sort_columns | 以字母表顺序绘制各列,默认使用当前列顺序 |
柱状图
#柱状图
fig,axes = plt.subplots(2,1)
data = Series(np.random.randn(16),index=list('abcdefghijklmnop'))
data.plot(kind='bar',ax=axes[0],color='k',alpha=0.7) #垂直柱状图
data.plot(kind='barh',ax=axes[1],color='k',alpha=0.7) #水平柱状图
df = DataFrame(np.random.rand(6,4),
index=['one','two','three','four','five','six'],
columns=pd.Index(['A','B','C','D'],name='Genus'))
df
df.plot(kind='bar')
df.plot(kind='barh',stacked=True,alpha=0.5) #堆积柱状图
直方图
pandas.hist()
tips = pd.read_csv('pydata-book-2nd-edition/examples/tips.csv')
tips['tip_pct'] = tips['tip']/tips['total_bill']
tips['tip_pct'].hist(bins=50)
密度图
kind = 'kde’
comp1 = np.random.normal(0,1,size=200) #N(0,1)
comp2 = np.random.normal(10,2,size=200) #N(10,4)
values = Series(np.concatenate([comp1,comp2]))
values.hist(bins=100,alpha=0.3,color='k',normed=True)
values.plot(kind='kde',style='k--')
散布图
plt.scatter()
macro = pd.read_csv('pydata-book-2nd-edition/examples/macrodata.csv')
data = macro[['cpi','m1','tbilrate','unemp']]
trans_data = np.log(data).diff().dropna()
trans_data[-5:]
plt.scatter(trans_data['m1'],trans_data['unemp'])
plt.title('Change in log %s vs. log %s' % ('m1','unemp'))
pd.plotting.scatter_matrix(trans_data,diagonal='kde',color='k',alpha=0.3) #散布图矩阵