4.2 pandas與Matplotlib


 

 

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]:
 
  Unnamed: 0 open close high low volume code
date              
2007-03-01 0 21.878 20.473 22.302 20.040 1977633.51 601318
2007-03-02 1 20.565 20.307 20.758 20.075 425048.32 601318
2007-03-05 2 20.119 19.419 20.202 19.047 419196.74 601318
2007-03-06 3 19.253 19.800 20.128 19.143 297727.88 601318
2007-03-07 4 19.817 20.338 20.522 19.651 287463.78 601318
... ... ... ... ... ... ... ...
2017-12-11 2558 71.200 73.250 73.310 70.820 1139927.00 601318
2017-12-12 2559 73.250 71.210 73.560 71.170 777900.00 601318
2017-12-13 2560 71.210 72.120 72.620 70.200 865117.00 601318
2017-12-14 2561 72.120 71.010 72.160 70.600 676186.00 601318
2017-12-15 2562 70.690 70.380 71.440 70.050 735547.00 601318

2563 rows × 7 columns

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()
 
c:\program files\python37\lib\site-packages\IPython\core\pylabtools.py:132: UserWarning: Creating legend with loc="best" can be slow with large amounts of data.
  fig.canvas.print_figure(bytes_io, **kw)
 
 

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()
 
c:\program files\python37\lib\site-packages\ipykernel_launcher.py:11: UserWarning: Matplotlib is currently using module://ipykernel.pylab.backend_inline, which is a non-GUI backend, so cannot show the figure.
  # This is added back by InteractiveShellApp.init_path()
 
In [ ]:
 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM