Python - matplotlib 資料視覺效果

來源:互聯網
上載者:User

標籤:data   資訊   建立   book   str   scipy   div   標準   legend   

在許多實際問題中,經常要對給出的資料進行可視化,便於觀察。

今天專門針對Python中的資料視覺效果模組--matplotlib這塊內容系統的整理,方便尋找使用。本文來自於對《利用python進行資料分析》以及網上一些部落格的總結。

 

1  matplotlib簡介matplotlib是Pythom可視化程式庫的泰鬥,經過幾十年它仍然是Python使用者最常用的畫圖庫。有許多別的程式庫都是建立在它的基礎上或直接調用它,比如pandas和seaborn就是matplotlib的外包,它們讓你使用更少的代碼去使用matplotlib的方法。Gallery頁面中有上百幅縮圖,開啟之後都有來源程式,非常適合學習matplotlib。 2  圖和子圖的建立2.1  匯入matplotlib
import matplotlib.pyplot as plt
import numpy as np

  

2.2  建立圖和子圖方式一plt.plot( )會在最近的一個圖上進行繪製
from numpy.random import randn  fig = plt.figure(figsize = (8,4))    #設定圖的大小  ax1 = fig.add_subplot(2,2,1)  ax2 = fig.add_subplot(2,2,2)  ax3 = fig.add_subplot(2,1,2)  ax3.plot(randn(50).cumsum(),‘k--‘)   # plt.plot(randn(50).cumsum(),‘k--‘)等效  ax1.hist(randn(100),bins = 10, color = ‘b‘, alpha = 0.3)      #bins 分成多少間隔   alpha 透明度  ax2.scatter(np.arange(30),np.arange(30) + 3*randn(30))  plt.show() 

 

2.3 建立子圖方式二
from numpy.random import randn  fig, axes = plt.subplots(2,2)                               #以數組方式訪問  t = np.arange(0., 5., 0.2)  axes[0,0].plot(t, t, ‘r-o‘, t, t**2, ‘bs‘, t, t**3, ‘g^‘)   #同時繪製多條曲線  axes[1,1].plot(randn(40).cumsum(),‘b--‘)  plt.show()  

 

2.4 主題設定

使用style.use()函數

df_iris = pd.read_csv(‘../input/iris.csv‘)  plt.style.use(‘ggplot‘)    #‘fivethirtyeight‘,‘ggplot‘,‘dark_background‘,‘bmh‘  df_iris.hist(‘sepal length‘)  plt.show()  

 

3  顏色、標記、線型、刻度、標籤和圖例
from numpy.random import randn  fig = plt.figure()  ax1 = fig.add_subplot(1,1,1)  ax1.plot(randn(30).cumsum(),color = ‘b‘,linestyle = ‘--‘,marker = ‘o‘,label = ‘$cumsum$‘)  # 線型  可以直接‘k--o‘  ax1.set_xlim(10,25)                                                                                     ax1.set_title(‘My first plot‘)  ax1.set_xlabel(‘Stages‘)  plt.legend(loc = ‘best‘)           #把圖放在不礙事的地方  xticks([])設定刻度  plt.show()  

  

等價於下面的代碼:

from numpy.random import randn  fig = plt.figure()  ax1 = fig.add_subplot(1,1,1)  ax1.plot(randn(30).cumsum(),color = ‘b‘,linestyle = ‘--‘,marker = ‘o‘,label = ‘$cumsum$‘)   #表徵圖可以使用latex內嵌公式  plt.xlim(10,25)                   #plt.axis([10,25,0,10])對x,y軸範圍同時進行設定  plt.title(‘My first plot‘)  plt.xlabel(‘Stages‘)  plt.legend(loc = ‘best‘)  plt.show()  

  

4  pandas中的繪圖函數在pandas中,我們具有列標籤,欄標籤以及分組資訊。這也就是說,要製作一張完整的圖表,原本需要一大堆的matplotlib代碼,現在只需一兩條簡潔的語句就可以了。pandas有很多能夠利用DataFrame對象資料群組織特點來建立標準圖表的進階繪圖方法。 4.1  線型圖
from numpy.random import randn  fig, axes = plt.subplots(1,2)  s = pd.Series(randn(10).cumsum(),index = np.arange(0,100,10))  s.plot(ax = axes[0])   # ax參數選擇子圖    df = pd.DataFrame(randn(10,3).cumsum(0),columns = [‘A‘,‘B‘,‘C‘],index = np.arange(0,100,10))  df.plot(ax = axes[1])      plt.show()  

 

4.2 柱狀圖
from numpy.random import rand  fig, axes = plt.subplots(1,2)  data = pd.Series(rand(16),index = list(‘abcdefghijklmnop‘))  data.plot(kind = ‘bar‘, ax = axes[0], color = ‘b‘, alpha = 0.7)    #kind選擇圖表類型  ‘bar‘ 垂直柱狀圖  data.plot(kind = ‘barh‘, ax = axes[1], color = ‘b‘, alpha = 0.7)   # ‘barh‘ 水平柱狀圖  plt.show() 

  

from numpy.random import rand  fig, axes = plt.subplots(1,2)  data = pd.DataFrame(rand(6,4),                      index = [‘one‘,‘two‘,‘three‘,‘four‘,‘five‘,‘six‘],                      columns = pd.Index([‘A‘,‘B‘,‘C‘,‘D‘], name = ‘Genus‘))  data.plot(kind = ‘bar‘, ax = axes[0], alpha = 0.5)  data.plot(kind = ‘bar‘, ax = axes[1], stacked = True, alpha = 0.5)  plt.show()  

 

此外,柱狀圖有一個非常不錯的用法,利用value_counts( )圖形化顯示Series中各值的出現機率,比如s.value_counts( ).plot(kind = ‘bar‘)。

 

4.3 長條圖和密度圖
from numpy.random import randn  fig, axes = plt.subplots(1,2)  data = pd.Series(randn(100))  data.hist(ax = axes[0], bins = 50)       #長條圖  data.plot(kind = ‘kde‘, ax = axes[1])    #密度圖  plt.show()  

 其實可以一次性製作多個長條圖,layout參數的意思是將兩個圖分成兩行一列,如果沒有這個參數,預設會將全部的圖放在同一行。

 

df_iris = pd.read_csv(‘../input/iris.csv‘)  columns = [‘sepal length‘,‘sepal width‘,‘petal length‘,‘petal width‘]  df_iris.hist(column=columns, layout=(2,2))  plt.show()  

  

4.4 箱型圖箱型圖是基於五數概括法(最小值,第一個四分位元,第一個四分位元(中位元),第三個四分位元,最大值)的資料的一個圖形匯總,還需要用到四分位元間距IQR = 第三個四分位元 - 第一個四分位元。
df_iris = pd.read_csv(‘../input/iris.csv‘)  #[‘sepal length‘,‘sepal width‘,‘petal length‘,‘petal width‘,‘class‘]  sample_size = df_iris[[‘petal width‘,‘class‘]]  sample_size.boxplot(by=‘class‘)  plt.xticks(rotation=90)                     #將X軸的座標文字旋轉90度,垂直顯示  plt.show()  

  

5  參考資料連結
  • Gallery頁面
  • matplotlib — 繪製精美的圖表
  • Python — matplotlib繪圖可視化知識點整理
  • Python資料視覺效果之matplotlib學習筆記
  • 53814635   (僅為記錄,方便尋找使用)
 

Python - matplotlib 資料視覺效果

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.