pandas與Matplotlib¶
In [2]:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
In [6]:
pd.read_csv('601318.csv',parse_dates=['date'],index_col='date')
Out[6]:
In [12]:
df = pd.read_csv('601318.csv',parse_dates=['date'],index_col='date')['2017']
df.plot()
plt.show()
使用matplotlib實例—繪制數學函數圖像¶
使用 Matplotlib模塊在一個窗口中繪制數學函數y=x,y=y=3×^3+5×^2+2x+1的圖像,使用不同顏色的線加以區別,並使用圖例說明各個線代表什么函數。
In [15]:
x = np.linspace(-1000,1000,100000)
y1 = x.copy()
y2 = x**2
y3 = x**3 + 5*x**2 + 2*x + 4
plt.plot(x,y1,color='red',label='y=x')
plt.plot(x,y2,color='blue',label='y=^2')
plt.plot(x,y3,color='green',label='x^3+x^2+2x+4')
plt.xlim(-1000,1000)
plt.ylim(-1000,1000)
plt.legend()
plt.show()
matplotlib 畫布與子圖¶
畫布:fig
fig = plt.figure()
圖:subplot
ax1= fig.add_subplot(2,2,1)
調節子圖間距
subplots_ adjust(left, bottom, right, top, space, hspace)
In [28]:
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax1.plot([1,2,3,4],[5,6,7,8])
ax2 = fig.add_subplot(2,2,2)
plt.show()
matplotlib 柱狀圖和餅圖¶
支持的圖形
函數 | 說明 |
---|---|
plt.plot(x,y,fmt…) | 坐標圖 |
plt.boxplot(data,notch,position) | 箱型圖 |
plt.bar(left,height,width,bottom) | 條形圖 |
plt.barh(width,bottom,left,height) | 橫向條形圖 |
plt.polar(theta,r) | 極坐標圖 |
plt.pie(data, explode) | 餅圖 |
plt.psd(x,NFFT=256,pad_to,Fs) | 功率譜密度圖 |
plt.specgram(x,NFFT=256,pad_to,F) | 譜圖 |
plt.cohere(x,y,NFFT=256,Fs) | X-Y相關性函數 |
plt.scatter(x,y) | 散點圖 |
plt.step(x, y, where) | 步階圖 |
plt.hist(x, bins, normed) | 直方圖 |
In [52]:
plt.bar([1,2,4,5],[2,3,4,5])
plt.show()
In [53]:
data = [32,48,21,100]
label=['Jan','Feb','Mar','Apr']
plt.bar(np.arange(len(data)),data)
plt.xticks(np.arange(len(data)),label)
plt.show()
In [54]:
data = [32,48,21,100]
label=['Jan','Feb','Mar','Apr']
plt.bar(np.arange(len(data)),data,width=0.5)
plt.xticks(np.arange(len(data)),label)
plt.show()
In [55]:
data = [32,48,21,100]
label=['Jan','Feb','Mar','Apr']
plt.bar(np.arange(len(data)),data,align='edge')
plt.xticks(np.arange(len(data)),label)
plt.show()
In [58]:
plt.pie([10,20,30,40],labels=['a','b','c','d'])
plt.show()
In [62]:
plt.pie([10,20,30,40],labels=['a','b','c','d'],autopct="%.f%%")
plt.show()
In [61]:
plt.pie([10,20,30,40],labels=['a','b','c','d'],autopct="%.2f%%")
plt.show()
In [70]:
plt.pie([10,20,30,40],labels=['a','b','c','d'],autopct="%.2f%%",explode=[0,0,0.1,0.1])
plt.show()
In [74]:
plt.pie([10,20,30,40],labels=['a','b','c','d'],autopct="%.2f%%",explode=[0.1,0,0.1,0])
plt.axis('equal')
plt.show()
matplotlib K線圖¶
matplotlib.finanace 子包中有許多繪制金融相關圖的函數接口。
繪制K線圖:matplotlib.finance.candlestick_ochl 函數
In [91]:
from matplotlib.dates import date2num
import mpl_finance as fin # pip install mplfinance mpl_finance
df = pd.read_csv('601318.csv',parse_dates=['date'],index_col='date')
df = df.iloc[:10,:]
df['time'] = date2num(df.index.to_pydatetime())
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
arr = df[['time','open','close','high','low']].values
fin.candlestick_ochl(ax1,arr)
fig.show()
In [ ]: