Matplotlib:繪圖和可視化

Matplotlib:繪圖和可視化

undefined

  • 簡介
  • 簡單繪製線形圖
  • plot函數
  • 支持圖類型
  • 保存圖表

一 、簡介

undefined

Matplotlib是一個強大的Python繪圖和數據可視化的工具包。數據可視化也是咱們數據分析的最重要的工做之一,能夠幫助咱們完成不少操做,例如:找出異常值、必要的一些數據轉換等。完成數據分析的最終結果也許就是作一個可交互的數據可視化。數組

安裝方式:dom

pip install matplotlibsvg

引用方法:函數

import matplotlib.pyplot as plt工具

二 、簡單繪製線形圖

plt.plot()   # 繪圖函數
plt.show()   # 顯示圖像

在jupyter notebook中不執行這條語句也是能夠將圖形展現出來3d

import matplotlib.pyplot as plt
import numpy as np
data = np.arange(10)
plt.plot(data)
plt.show() # 顯示圖像,在notebook中不執行這一句也能夠

執行結果:code

undefined

雖然seaborn這些庫和pandas的內置繪圖函數可以處理許多普通的繪圖任務,若是須要自定義一些高級功能的話就必需要matplotlib API.orm

undefined

三 、plot函數

3.1 plot函數:繪製折線圖

  • 線型linestyle(-,-.,-–,..)
  • 點型marker(v,^,s,*,H,+,X,D,O,..…)
  • 顏色color(b,g,r,y,k,w,..…)
plt.plot([0,3,9,15,30],linestyle = '-.',color = 'r',marker = 'o')

undefined

3.2 圖像標註

方法 描述
plt.title() 設置圖像標題
plt.xlabel() 設置x軸名稱
plt.ylabel() 設置y軸名稱
plt.xlim() 設置x軸範圍
plt.ylim() 設置y軸範圍
plt.xticks() 設置x軸刻度
plt.yticks() 設置y軸刻度
plt.legend() 設置曲線圖例
plt.plot([0,3,9,15,30],linestyle = '-.',color = 'r',marker = 'o',label="A") 
plt.plot([1,3,16,23,30],[30,23,13,25,30],label='B')
plt.title("Title")  # 標題
plt.xlabel('X')  # x軸名稱
plt.ylabel('Y')  # y軸名稱

plt.xticks(np.arange(0,30,2))  # x軸刻度
plt.xlim(-0.2,10,2)  # x軸範圍
plt.legend()  # 曲線圖例

運行圖例:對象

undefined

3.3 繪製數學函數

使用Matplotlib模塊在一個窗口中繪製數學函數y=x, y=x**2,y=sinx的圖像,使用不一樣顏色的線加以區別,並使用圖例說明各個線表明什麼函數。blog

x = np.arange(-100,100)
y1 = x
y2 = x ** 2
y3 = np.sin(x)
-----------------------
plt.plot(x,y1,label="y=x")
plt.plot(x,y2,label="y=x^2")
plt.plot(x,y3,label="y=sin(x)")

plt.ylim(-100,100)
plt.legend()

undefined

四 、支持的圖類型

undefined

函數 說明
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) 直方圖
# 柱狀圖
data = [12,34,23,54]
labels = ['Jan','Fed','Mar','Apr']
plt.xticks([0,1,2,3],labels)  # 設置x軸刻度
plt.bar([0,1,2,3],data)

undefined

# 橫向柱狀圖
data = [12,34,23,54]
labels = ['Jan','Fed','Mar','Apr']
plt.yticks([0,1,2,3],labels)
plt.barh([0,1,2,3],data)

undefined

# DataFrame數組圖
df = pd.DataFrame({
    'Jan':pd.Series([1,2,3],index=['a','b','c']),
    'Fed':pd.Series([4,5,6],index=['b','a','c']),
    'Mar':pd.Series([7,8,9],index=['b','a','c']),
    'Apr':pd.Series([2,4,6],index=['b','a','c'])
})
df.plot.bar()  # 水平柱狀圖,將每一行中的值分組到並排的柱子中的一組
df.plot.barh(stacked=True,alpha=0.5)  # 橫向柱狀圖,將每一行的值堆積到一塊兒

undefined

# 餅圖
plt.pie([10,20,30,40],labels=list('abcd'),autopct="%.2f%%",explode=[0.1,0,0,0])  # 餅圖
plt.axis("equal")
plt.show()

undefined

# 散點圖
import random
x = np.random.randn(100)
y = np.random.randn(100)
plt.scatter(x,y)

undefined

五 、保存圖表到文件

5.1 plt.savafig(‘文件名.拓展名’)

文件類型是經過文件擴展名推斷出來的。所以,若是你使用的是.pdf,就會獲得一個PDF文件。

plt.savefig('123.pdf')

savefig並不是必定要寫入磁盤,也能夠寫入任何文件型的對象,好比BytesIO:

from io import BytesIO
buffer = BytesIO()
plt.savefig(buffer)
plot_data = buffer.getvalue()
參數 說明
fname 含有文件路徑的字符串或者Python的文件型對象。
dpi 圖像分辨率,默認爲100
format 顯示設置文件格式(「png」,「jpg」,「pdf」,「svg」,「ps」,..…)
facecolor、edgecolor 背景色,默認爲「W」(白色)
bbox_inches 圖表須要保存的部分。設置爲」tight「,則嘗試剪除圖表周圍空白部分

undefined

相關文章
相關標籤/搜索