天天看點

matplotlib基礎學習筆記(1)

import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline   # juyter調用matplotlib.pyplot畫圖所需
           

關于 %matplotlib 詳情。(https://www.jianshu.com/p/2dda5bb8ce7d)

本筆記所用圖檔都是通過plt.savefig()函數儲存。

用plt.figure建立一個新的figure,再在上面add_subplot一個或多個subplot。

fig = plt.figure() #建立一個figuer
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
           
matplotlib基礎學習筆記(1)

在已經建立好的subplot上面畫圖。

from numpy.random import randn
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(randn(50).cumsum(),'k--') 
_ = ax1.hist(randn(100),bins=20,alpha=0.3)
ax2.scatter(np.arange(30),np.arange(30)+3*randn(30))
           
matplotlib基礎學習筆記(1)

使用plt.subplot(a,b)将圖表劃分,a表示橫向劃分為a個,b表示縱向劃分為b個。

fig = plt.subplots(2,3)
           
matplotlib基礎學習筆記(1)

使用subplots_adjust方法修改其間距。

plt.subplots_adjust(wspace=0,hspace=0)
           
matplotlib基礎學習筆記(1)

設定figure大小,調整橫縱坐标刻度,添加元素标簽和注解,以及設定圖表标題。

fig = plt.figure(figsize=(12,6))
ax = fig.add_subplot(1,1,1)
ax.set_xticks([0,250,500,750,1000])  # set_xticks([1,2,3])設定橫坐标刻度
ax.set_yticks([-10,0,10,20,30])  # set_yticks([1,2,3])設定縱坐标刻度
ax.plot(randn(1000).cumsum(),label='one') #label=‘元素标簽’
ax.set_xlabel('橫坐标') #設定橫坐标名字
ax.set_ylabel('縱坐标') #設定縱坐标名字
ax.set_title('标題') #設定圖檔标題
ax.legend(loc='best')
ax.text(250,5,'hello world!',family='monospace',fontsize=20)#添加注解
           
matplotlib基礎學習筆記(1)

具體執行個體:

from datetime import datetime
import pandas as pd
fig = plt.figure(figsize=(16,6))
ax1 = fig.add_subplot(1,1,1)
                                                                      # parse_dates 是讀取時間格式轉換
data = pd.read_csv('/Users/lc3/Desktop/pydata-book-2nd-edition/examples/spx.csv',index_col=0,parse_dates=True)
spx = data['SPX']
spx.plot(ax=ax1,style='g-')

crisis_data = [ (datetime(2007,10,11),'牛市高峰期'),
                (datetime(2008, 3,12),'貝爾斯登破産'),
                (datetime(2008, 9, 5),'雷曼破産')]

for date,label in crisis_data:
    ax1.annotate(label, xy=(date, spx.asof(date) + 50), # .asof() 參數為日期或時間
                xytext=(date, spx.asof(date) + 200),
                arrowprops=(dict(facecolor='black')),
                horizontalalignment='left', verticalalignment='top')
ax1.set_xlim(['10/1/2007','1/1/2009'])
ax1.set_ylim([1000,1800])

plt.savefig('analysis.png', dpi=800,bbox_inches='tight') #将圖表儲存至檔案  dpi是分辨率f
           
matplotlib基礎學習筆記(1)

figure上面畫形狀。

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(1,1,1)

#alpha	圖表的填充不透明(0-1)
rect = plt.Rectangle((0.2,0.6),0.4,0.2,color='r',alpha=0.1)
circ = plt.Circle((0.2,0.2),0.2,color='g',alpha=0.3)
pgon = plt.Polygon([[1.0,0.05],[0.8,0.05],[0.8,0.4]],color='k',alpha=0.5)

ax.add_patch(rect)
ax.add_patch(circ)
ax.add_patch(pgon)
           
matplotlib基礎學習筆記(1)

通過plt.savefig()方法,在Web上提供動态生成圖檔的代碼:

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