matplotlib 初步學習



author:pprp

Matplotlib數據可視化

目錄

安裝

  • conda install matplotlib
  • sudo apt-get install python-matplotlib

架構

  1. scripting
  2. Artist
  3. backend

Backend層

  • FigureCanvas對象實現繪圖區域
  • Renderer在FigureCanvas上繪圖
  • Event處理用戶輸入

Artist層

圖中能看到的元素都是這個層的,比如標題,標簽,刻度等

分為兩種:

  1. primitive 原始
  2. composite 復合
graph TB Axes-->Figure Text-->Axes X-axis-->Axes Y-axis-->Axes Line2D-->Axes Y-ticks-->Y-axis Y-label-->Y-axis X-ticks-->X-axis X-label-->X-axis

Scripting層

pyplot, 數據分析和可視化

  • pylab & pyplot

    • from pylab import *
    • import matplotlib.pyplot as plt
    • import numpy as np
  • pylab 在一個命名空間整合了pyplot和numpy的功能,無需單獨倒入numpy

    建議使用pylab模塊進行使用

pyplot模塊

交互式用法與MATLAB相似

生成一個簡單的交互式圖表

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.show()

設置圖形的屬性

  • plt.axis([fromx,tox,fromy,toy]) # 范圍
  • plt.title('my first plot') # 設置標題
plt.plot([1,2,3,4],[1,4,9,16],'ro')
plt.show()

matplotlib and numpy

import math
import numpy as np
t=np.linspace(0,10,1000)
y1=map(math.sin,math.pi*t)
y2=map(math.sin,math.pi*t+math.pi/4)
y3=map(math.sin,math.pi*t-math.pi/4)
plt.plot(t,y1,'b*',t,y2,'g^',t,y3,'ys')

試了一下報錯了

RuntimeError: matplotlib does not support generators as input

import math
import numpy as np
x=np.linspace(0,10,1000)
y1=np.sin(x)+1
y2=np.cos(x ** 2)+1
y3=np.cos(x)
plt.plot(t,y1,'b*',t,y2,'g^',t,y3,'ys')

從網上找的一個例子:

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei']#用來正常顯示中文標簽
plt.rcParams['axes.unicode_minus']=False#用來正常顯示負號

x = np.linspace(0, 10, 1000)
y = np.sin(x) + 1
z = np.cos(x ** 2) + 1

plt.figure(figsize = (8, 4))
plt.plot(x,y,label='$\sin x+1$', color = 'red', linewidth = 2)
plt.plot(x,z,'b--',label='$\cos x^2+1$')
plt.xlabel('Time(s)')
plt.ylabel('Volt')
plt.title('A Sample Example')
plt.ylim(0,2.2)
plt.xlim(0,10)
plt.legend(loc='best')
顏色字符 說明 顏色字符 說明.1
0 'b' blue 'm' magenta洋紅色
1 'g' green 'y' 黃色
2 'r' red 'k' 黑色
0 '-' 實線
1 '--' 破折線
2 '-.' 點划線
3 ':' 虛線
標記字符 說明 標記字符 說明 標記字符 說明
'.' 點標記 '1' 下花三角標記 'h' 豎六邊形標記
',' 像素標記(極小點) '2' 上花三角標記 'H' 橫六邊形標記
'o' 實心圏標記 '3' 左花三角標記 '+' 十字形標記
'v' 倒三角標記 '4' 右花三角標記 'x' x標記
'^' 上三角標記 's' 實心方形標記 'D' 菱形標記
'>' 右三角標記 'p' 實心五角標記 'd' 瘦菱形標記
'<' 左三角標記 '*' 星形標記 ' '

pyplot並不默認支持中文顯示,需要rcParams修改字體實現

matplotlib.rcParams['font.family']='SimHei'

rcParams['font.family']

中文字體 說明
'SimHei' 中文黑體
'Kaiti' 中文楷體
'LiSu' 中文隸書
'FangSong' 中文仿宋
'YouYuan' 中文幼圓
STSong 華文宋體

使用kwarg

關鍵字參數

plt.plot([1,2,3,3,2,6,0,2],linewidth=2.0)

處理多個Figure和Axes對象

t=np.arange(0,5,0.1)
y1=np.sin(2*np.pi*t)
y2=np.sin(2*np.pi*t)

plt.subplot(211)
plt.plot(t,y1,'b-.')
plt.subplot(212)
plt.plot(t,y2,'r--')

subplot(numRows, numCols, plotNum)

參考

import numpy as np
import matplotlib.pyplot as plt
# 分成2x2,占用第一個,即第一行第一列的子圖
plt.subplot(221)
# 分成2x2,占用第二個,即第一行第二列的子圖
plt.subplot(222)
# 分成2x1,占用第二個,即第二行
plt.subplot(212)

試一試:

import matplotlib.pyplot as plt
import numpy as np


# plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
# plt.axis([0, 6, 0, 20])
# plt.show()

# t = np.arange(0., 5., 0.2)
# plt.plot(t, t, 'r--', t, t ** 2, 'bs', t, t ** 3, 'g^')


def f(t):
    return np.exp(-t) * np.cos(2 * np.pi * t)


t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)

plt.figure(12)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--')

plt.subplot(222)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')

plt.subplot(212)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

為圖表添加更多元素

文本的添加

plt.title('title')
plt.xlabel('counting')
plt.ylabel('sqare values')
fontsize=20,fontname='Times New Roman'
color='gray'
# 還允許你在表格的任何位置添加文本
text(x,y,s,fontdict=None,**kwargs)

支持LaTeX表達式

將表達式內容放在兩$符號之間,就可以用latex表達式了,通常要在表達式前加上r,表明它后面是原是文本,不能對其進行轉義操作。

plt.text(1.1,12,r'$y=x^2$',fontsize=20,bbox={'facecolor':'yellow','alpha':0.2})

添加網格

plt.grid(True)

添加圖例

plt.legend(['Fisrt Series'])
# 默認添加到右上角
# loc 關鍵字可以控制位置: 0 最佳位置,9 上方水平居中,8 下方水平居中

保存圖標

%save my_first_chart 171
# 加載
%load my_first_chart.py
# 運行
%run my_first_chart.py

保存為圖片

plt.savefig('mychart.png')

處理日期值

import datatime

datatime.data(2015,3,21)

在圖表中可能有點問題,顯示不全

再引入import matplotlib.dates,用MonthLocator()和DayLocator()函數分別表示月份和日子,然后用DateFormatter()函數

定義好兩個時間尺度,一個用於日期,一個用於月份,可以調用set_major_locator()函數和set_minor_locator()函數,為x軸設置兩個不同的標簽;月份刻度標簽的設置需要用到set_major_formatter()函數

import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

months=mdates.MonthLocator()
days=mdates.DayLocator()

timeFmt=mdates.DateFormatter('%Y-%m')
events=[datetime.date(2015,1,23),datetime.date(2015,1,28),datetime.date(2015,2,3),datetime.date(2015,2,21),datetime.date(2015,3,15),datetime.date(2015,3,24),datetime.date(2015,4,8),datetime.date(2015,4,24)]
readings=[12,22,25,20,18,15,18,14]
fig,ax=plt.subplots()
plt.plot(events,readings)
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(timeFmt)
ax.xaxis.set_minor_locator(days)

圖表類型

線性圖

import matplotlib.pyplot as plt
import numpy as np
x=np.arange(-2*np.pi,2*np.pi,0.01)
y=np.sin(3*x)/x
plt.plot(x,y)

刻度的自定義:

xticks(), yticks()
plt.xticks([-2*np.pi,-np*pi,0,np.pi,2*np.pi],[r'$-2\pi$',r'$-\pi$',0,'$\pi$','$2\pi$'])

image

想要將坐標軸改變,需要用gca()函數

ax=plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

annotate() 函數可以用來注釋,添加箭頭

直方圖

hist() 函數
pop = np.random.randint(0,100,100)
n,bins,patches=plt.hist(pop,bins=20)

條狀圖

bar() 函數
index=np.arange(5)
values1=[5,7,3,4,6]
plt.bar(index,values1)
plt.xticks(index+0.4,['A','B','C','D','E'])

水平條狀圖

barh() 函數
index=np.arange(5)
values1=[5,7,3,4,6]
plt.barh(index,values1)
plt.xticks(index+0.4,['A','B','C','D','E'])

多序列條狀圖

index=np.arange(5)
v1=[5,7,3,4,6]
v2=[5,6,6,4,7]
v3=[5,6,5,4,6]
bw=0.3
plt.axis([0,5,0,8])
plt.bar(index,v1,bw,color='b')
plt.bar(index+bw,v2,bw,color='g')
plt.bar(index+2*bw,v3,bw,color='r')
plt.xticks(index+1.5*bw,['A','B','C','D','E'])

DataFrame的多序列條狀圖:

data是字典 'series1':[1,2,3,4]

df=pd.DataFrame(data)

df.plot(kind='bar')

餅圖

pie()函數
labels=['Nokia','Samsung','Apple','Lumia']
values=[10,30,45,15]
colors=['yellow','red','blue','green']
plt.pie(values,labels=labels,colors=colors)
plt.axis('equal')

# 突出某一塊		
explode=[0.3,0,0,0]
plt.pie(values,labels=labels,colors=colors,explode=explode,startangle=180)

等值線圖

contour()函數

def f(x,y):
	return (1-y**5+x**5)*np.exp(-x**2-y**2)
dx=0.01
dy=0.01
x=np.arange(-2.0,2.0,dx)
y=np.arange(-2.0,2.0,dy)
X,Y=np.meshgrid(x,y)
C=plt.contour(X,Y,f(X,Y),8,colors='black')
plt.contourf(X,Y,f(X,Y),8,cmap=plt.cm.hot)
plt.clabel(C,inline=1,fontsize=10)
plt.colorbar()

mplot3D

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig=plt.figure()
ax=Axes3D(fig)
X=np.arange(-2,2,0.1)
Y=np.arange(-2,2,0.1)
X,Y=np.meshgrid(X,Y)
def f(x,y):
	return (1-y**5+x**5)*np.exp(-x**2-y**2)
ax.plot_surface(X,Y,f(X,Y),rstride=1,cstride=1)

3D散點圖

scatter()函數

3D條狀圖

bar()函數

多面板圖形

在一個圖中顯示另一個子圖

fig=plt.figure()
ax=fig.add_axes([0.1,0.1,0.8,0.8])
inner_ax=fig.add_axes([0.6,0.6,0.25,0.25])

子圖網格

GridSpec()函數
gs=plt.GridSpec(3,3)
fig=plt.figure(figsize=(6,6))
fig.add_subplot(gs[1,:2])
fig.add_subplot(gs[0,:2])
fig.add_subplot(gs[2,0])
fig.add_subplot(gs[:2,2])
fig.add_subplot(gs[2,1:])


免責聲明!

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



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