數據可視化——基於matplotlib庫

以下示例都基於進行了import操作

import matplotlib.pyplot as plt

 

常用函數

  • plt.plot(x,y,, color='green', marker='o', linestyle='dashed', linewidth=2, markersize=12,alpha=0.2,label='line')

參數:自變量,因變量,顏色,點樣式,線類型,線寬\點粗細,點大小,透明度(0到1變深),圖例說明

color還可以是:歸一化RGB元組(0.1,0.2,0.3),十六進制字符串‘#eeefff’

可通過help(plt.plot)獲得幫助,比如plt.plot(x,y,'go'):‘go’代表綠色圓點

    =============    ===============================
    character        color
    =============    ===============================
    ``'b'``          blue
    ``'g'``          green
    ``'r'``          red
    ``'c'``          cyan
    ``'m'``          magenta
    ``'y'``          yellow
    ``'k'``          black
    ``'w'``          white
    =============    ===============================

    =============    ===============================
    character        description
    =============    ===============================
    ``'.'``          point marker
    ``','``          pixel marker
    ``'o'``          circle marker
    ``'v'``          triangle_down marker
    ``'^'``          triangle_up marker
    ``'<'``          triangle_left marker
    ``'>'``          triangle_right marker
    ``'1'``          tri_down marker
    ``'2'``          tri_up marker
    ``'3'``          tri_left marker
    ``'4'``          tri_right marker
    ``'s'``          square marker
    ``'p'``          pentagon marker
    ``'*'``          star marker
    ``'h'``          hexagon1 marker
    ``'H'``          hexagon2 marker
    ``'+'``          plus marker
    ``'x'``          x marker
    ``'D'``          diamond marker
    ``'d'``          thin_diamond marker
    ``'|'``          vline marker
    ``'_'``          hline marker
    =============    ===============================

    =============    ===============================
    character        description
    =============    ===============================
    ``'-'``          solid line style
    ``'--'``         dashed line style
    ``'-.'``         dash-dot line style
    ``':'``          dotted line style
    =============    ===============================
  • plt.title()

添加標題

  • plt.axis([xmin, xmax, ymin,ymax])

限定座標軸範圍

  • plt.xlabel('x')

橫軸標籤

  • plt.ylabel('y')

縱軸標籤

  • plt.legend()

顯示標籤作爲圖例,需要在plt.plot中設置label

  • plt.grid(alpha=0.3)

顯示網格

  • plt.annotate()

加註釋

  • plt.style.use('ggplot')

設置作圖風格,可通過print(plt.style.available)獲得幫助

  • plt.subplot(224)

子圖,2行2列第四個,後面常常跟plt.plot語句作圖

  • plt.subplots

fig,ax = plt.subplots()等價於:

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

更多參見https://blog.csdn.net/xavier_muse/article/details/83859272

  • .fill

繪製填充圖,下例分別用了subplots和subplot來實現fill操作

x=np.linspace(0,1,500)
y=np.sin(4*np.pi*x)*np.exp(-5*x)
#
# plt.subplot(111)
# plt.fill(x,y)

fig,ax=plt.subplots()
ax.fill(x,y)

plt.show()
  • plt.show()

展示圖像

  • plt.ion()交互模式畫多張圖

https://blog.csdn.net/zbrwhut/article/details/80625702

結合pandas繪圖

將numpy數據傳入pandas.DataFrame,可便捷作圖

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

DATA=np.random.randint(0,5,(10,4))
print(DATA)
df=pd.DataFrame(DATA,columns=['A','B','C','D'])

#折線圖
# df.plot(alpha=1,linewidth=1.5)
#箱線圖
# df.iloc[:,:].boxplot()
#直方圖
# df.hist(bins=50)#bins調整柱間距離,各列分開繪製
# df.plot.bar()#各列繪製在一張圖中
# df.plot.barh(stacked=True)#各列水平碼放的柱狀圖
#散點圖
df.plot.scatter(x='A',y="B",s=df['C']*100)#三個參數分別爲x軸數據,y軸數據,點大小

plt.show()

除pandas外還可結合seaborn進行便捷作圖

詞雲圖

代碼及相關資源:

https://github.com/shenxiangzhuang/PythonDataAnalysis/tree/master/Ch3Analysis-Visualization/Visualization

上面鏈接運行一下MwordClound.py即可

jieba是一箇中文分詞庫,wordcloud庫用來生成詞雲圖

 

 

常見問題:

  • 在matplotlib.py中import matplotlib.pyplot as plt報錯:

No module named 'matplotlib.pyplot'; 'matplotlib' is not a package

cannot import name 'pyplot'

解決辦法:將py文件改名

 

  • 中文顯示

windows和linux的解決方法不同

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