2015-03-28-绘图和可视化(1)-matplotlib API入门

来源:互联网 发布:虚拟打印机端口删除 编辑:程序博客网 时间:2024/06/05 02:20
--
import numpy as np
import matplotlib.pyplot as plt
from numpy.random import randn


plot(np.arange(10))
---------------------------------------------------------------------------------------
-----(一)matplotlib API入门
-----1.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)


from numpy.random import randn
plt.plot(randn(50).cumsum(),'k--')


_=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
---------------------
pyplot.subplots的选项
--nrows subplot的行数
--ncols subplot的列数
--sharex 所有subplot应该使用相同的X轴刻度
--sharey 所有subplot应该使用相同的Y轴刻度
--subplot_kw 用于创建各subplot的关键字字典
--**fig_kw 创建figure时的其他关键字,如plt.subplots(2,2,figsize=(8,6))
---------------------
调整subplot周围的间距
subplots_adjust(left=None,bottom=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)


-----2.颜色、标记和线型
ax.plot(x,y,'g--')
ax.plot(x,y,linestype='--',color='g')


plt.plot(randn(30).cumsum(),'ko--')
plt.plot(randn(30).cumsum(),color='k',linestyle='--',marker='o')


drawstyle选项
data=randn(30).cumsum()
plt.plot(data,'k--',label='Default')
plt.plot(data,'k--',drawstyle='steps-post',label='steps-post')


-----3.刻度、标签和图例
fig=plt.figure();
ax=fig.add_subplot(1,1,1)
ax.plot(randn(1000).cumsum())


ticks=ax.set_xticks([0,250,500,750,1000])
labels=ax.set_xticklabels(['one','two','three','four','five'],
rotation=30,fontsize='small')


ax.set_title('My first matplotlib plot')
ax.set_xlabel('Stages')


添加图例
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='_nolegend')
ax.legend(loc='best')


-----4.注解以及在Subplot上绘图
ax.text(x,y,'Hello world!',family='monospace',fontsize=10)
2008-2009年金融危机期间的重要日期
import pandas as pd
from datetime import datetime
fig=plt.figure()
ax=fig.add_subplot(1,1,1)
data=pd.read_csv('ch08\spx.csv',index_col=0,parse_dates=True)
spx=data['SPX']
spx.plot(ax=ax,style='k-')
crisis_data=[
(datetime(2007,10,11),'Peak of bull market'),
(datetime(2008,3,12),'Bear Stearns Fails'),
(datetime(2008,9,15),'Lehman Bankruptcy')
]
for date,label in crisis_data:
    ax.annotate(label,xy=(date,spx.asof(date)+50),
xytext=(date,spx.asof(date)+200),
arrowprops=dict(facecolor='black'),
horizontalalignment='left',verticalalignment='top')

ax.set_xlim(['1/1/2007','1/1/2011'])
ax.set_ylim([600,1800])


ax.set_title('Important dates in 2008-2009 financial crisis')


图表中添加图形
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)
circ=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(circ)
ax.add_patch(pgon)


-----5.将图表保存到文件
plt.savefig('figpath.svg')
plt.savefig('figpath.png',dpi=400,bbox_inches='tight')


from io import StringIO
buffer=StringIO()
plt.savefig(buffer)
plot_data=buffer.getvalue()



-----6.matplotlib配置
plt.rc('figure',figsize=(10,10))
font_options={'family':'monospace',
'weight':'bold',
'size':10}
plt.rc('font',**font_options)






















0 0
原创粉丝点击