玩轉可視化繪圖 matplotlib簡單繪圖

matolotlib 基本圖形繪製

from pandas import Series,DataFrame
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

下面先做兩個例子繪折線圖

Series生成圖表

ts=Series(np.random.randn(120),index=pd.date_range('1/1/2018',periods=120))
ts=ts.cumsum()  
ts.head()
    2018-01-01    0.732337
    2018-01-02    1.222352
    2018-01-03    0.460722
    2018-01-04    0.694276
    2018-01-05    0.394703
    Freq: D, dtype: float64
ts.plot(kind='line',
       title='2018 time',
       label='2018',
       style='--g',
       color='red',
       alpha=0.5,
       grid=True,
       rot=60,
       ylim=[-30,50],
       yticks=list(range(-20,50,5)),
       use_index=True,
       figsize=(8,5),
       legend=True)

DataFrame生成圖表

df=DataFrame(np.random.randn(120,4),index=pd.date_range('1/1/2018',periods=120),columns=list('ABCD'))
df=df.cumsum()
df.head()  #查看前五行數據
A B C D
2018-01-01 1.796606 -0.105809 0.508237 -0.217147
2018-01-02 1.594785 -0.191255 -1.438882 -0.348196
2018-01-03 2.123106 0.311300 -1.532028 -0.719643
2018-01-04 1.209116 1.676585 -0.853266 -1.523482
2018-01-05 -0.165966 0.150911 -1.813108 0.114975
df.plot(kind='line',
       title='2018 time',
       label='2018',
       style='--',
       alpha=0.5,
       grid=True,
       rot=60,
       use_index=True,
       figsize=(15,8),
       fontsize='large',
       legend=True,
       subplots=False) 

繪圖標籤總結:

#Series.plot() series的index爲橫座標,value爲縱座標
#figsize:圖像大小標籤
#title:圖像標題名稱
#kind:line,bar 折線圖、柱狀圖等形狀設定
#label:爲圖例標籤,DataFrame是列名爲label圖例標籤
#style:風格字符串 包括linestyle,narker,color
#color:顏色
#alpha:透明度
#grid:圖表網格
#xlim 、ylim:x,y軸界限
#xticks,yticks:x,y刻度值
#legend:是否顯示圖例 使用plt.legend

下面練習簡單的圖形繪製

1. 柱狀圖與 堆疊圖

fig,axes=plt.subplots(4,1,figsize=(10,15)) #創建四個子圖
df1=Series(np.random.randint(0,10,16),index=list('abcdefghijklmnop'))
df2=DataFrame(np.random.rand(10,3),columns=['a','b','c'])

#單系列圖
df1.plot(kind='bar',grid=True,alpha=0.6,ax=axes[0])  #選擇第一個子圖

#多系列圖
df2.plot(kind='bar',alpha=0.5,ax=axes[1]) #選擇第二個子圖

#多系列圖和堆疊圖
df2.plot(kind='bar',colormap='Blues_r',edgecolor='green',stacked=True,ax=axes[2])#選擇第三個子圖

df2.plot.barh(ax=axes[3])

柱狀圖

2. 面積圖

fig,axes=plt.subplots(2,1,figsize=(8,6))
df3=DataFrame(np.random.rand(10,4),columns=['a','b','c','d'])  #正值的數據
df4=DataFrame(np.random.randn(10,4),columns=['a','b','c','d'])  #正值和負值都有的數據

df3.plot.area(alpha=0.5,ax=axes[0],colormap='Greens_r')
df4.plot.area(stacked=False,colormap='Set2',alpha=0.5,ax=axes[1])

#stacked 是否堆疊,默認區域圖是堆疊
#爲了產生堆積面積圖,每列需要是全部正值或者是全部是負值
#當數據有缺失na值時,會自動填充爲0

面積圖

3. 填充圖

fig,axes=plt.subplots(2,1,figsize=(8,6))
x=np.linspace(0,5*np.pi,1000)
y1=np.sin(x)
y2=np.sin(2*x)
axes[0].fill_between(x,y1,y2,color='g',alpha=0.5,label='area') #填充
axes[0].grid()

x2=np.arange(0.0,4.0*np.pi,0.01)
y2=np.sin(x2)
axes[1].plot(x2, y2)
axes[1].plot((x2.min(),x2.max()), (0,0)) #水平基準線
axes[1].fill_between(x2,y2,color='r',alpha=0.5)  #填充 
axes[1].grid()

填充圖

4. 餅圖

s=Series(2*np.random.rand(4),index=['a','b','c','d'],name='series')
plt.axis('equal') #讓圖形的長和寬相等
plt.pie(s,colors=['r','g','b','y'],
        explode=[0.1,0,0,0],  #每部分的偏移量
        labels=s.index,
        autopct='%.2f%%',  # 餅圖上的數據標籤顯示方式
        labeldistance=1.2, # 畫餅標記的直徑  默認1.1
        pctdistance=0.8,   # 每個切片的中心和通過autopct生成的文本開始之間的比例
        shadow=True,   #陰影
        startangle=0,   #開始角度
        radius=1.5,     #半徑
        frame=False)

print(s)
a    0.435720
b    0.888153
c    1.066442
d    1.867224
Name: series, dtype: float64

餅圖

5. 直方圖和密度圖

s1=Series(np.random.randn(1000))
s1.hist(bins=20,             #箱子寬度
      histtype='bar',        #風格 bar ,step
      align='mid',           #對齊方式 left  mid right 
      orientation='vertical',#水平還是垂直 horizontal ,vertical
      normed=True,       #標準化
       alpha=0.5)

#密度圖
s1.plot(kind='kde',style='k--',grid=True)   #密度圖時候    normed=True,  

直方圖和密度圖

6. 散點圖

plt.figure(figsize=(8,6))
x=2*np.random.randn(1000)
y=np.random.randn(1000)
plt.scatter(x,y,marker='.',
           s=np.random.randn(1000)*100,   #散點大小
           alpha=0.5,
            c=np.random.randn(1000)*100,  #散點顏色
           cmap='Reds')
plt.grid()

散點圖

7. 矩陣散點圖

ddf=DataFrame(np.random.randn(100,4),columns=['a','b','c','d'])
pd.plotting.scatter_matrix(ddf,figsize=(10,6),
                           marker='o',
                           diagonal='kde',#只能並且在 hist和kde 中選擇一個,每個指標的頻率圖
                           range_padding=0.1, #圖形在x軸和y軸原點的留白
                           alpha=0.6)

散點矩陣圖

8. 極座標圖

##創建數據
s= Series(np.arange(20))
theta=np.arange(0,2*np.pi,0.02)
#print(s.head())
#print(theta[:60])

#創建子座標
fig=plt.figure(figsize=(8,4))
ax1=plt.subplot(121,projection='polar')
ax2=plt.subplot(122,projection='polar')

#也可以這樣創建ax=fig.add_subplot(111,polar=True)

ax1.plot(theta,theta/6,linestyle='--',lw=2)  #lw爲線寬
#ax1.plot(s,linestyle='--',marker='.',lw=2)
ax2.plot(theta,theta/6,linestyle='--',lw=2)

#參數設定比較

#座標軸正方向,默認逆時針方向
ax2.set_theta_direction(-1) 

#設置極座標角度網格線顯示和標籤 ,其中網格和標籤數量一致
ax2.set_thetagrids(np.arange(0.0,360.0,90),['a','b','c','d'])

#設置網格線顯示,參數必須爲正數
ax2.set_rgrids(np.arange(0.2,2,0.2))

#設置角度偏移,逆時針  弧度
ax2.set_theta_offset(np.pi/2)

#設置極座標半徑範圍
ax2.set_rlim(0.2,1.8)

ax2.set_rmax(2) #極座標半徑的最大值

ax2.set_rticks(np.arange(0.1,1.5,0.2)) #極座標半徑網格線的顯示範圍

極座標圖

9. 箱線圖

fig,axes=plt.subplots(2,1,figsize=(10,6))
dff=DataFrame(np.random.rand(10,5),columns=['A','B','C','D','E'])
color=dict(boxes='DarkGreen',whiskers='DarkOrange',medians='DarkBlue',caps='Gray')

#boxes 箱線顏色
#whiskers 分位數與error bar橫線之間豎線的顏色
#medians 中位數線顏色
#caps  橫線顏色
dff.plot.box(ylim=[0,1.2],
            grid=True,
            color=color,
            ax=axes[0])

dff.plot.box(vert=False,        #vert 默認垂直,是否垂直
             positions=[1,4,9,8,6], #箱線圖佔位
            grid=True,
            color=color,
            ax=axes[1])

箱線圖

另外還有其他比較複雜的圖形繪製和繪圖參數的知識需要花時間熟悉進行學習,可以在matplotlib官網進行學習。

matplotlib官網網址:https://matplotlib.org/

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章