1. 程式人生 > >Python Matplotlib簡易教程

Python Matplotlib簡易教程

簡單演示

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50)
print(x)
y = 2*x + 1
# 第一個是橫座標的值,第二個是縱座標的值
plt.plot(x, y)
# 必要方法,用於將設定好的figure物件顯示出來
plt.show()

這裡寫圖片描述

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1, 1, 50)
y = 2**x + 1
# 第一個是橫座標的值,第二個是縱座標的值 plt.plot(x, y) plt.show()

這裡寫圖片描述

顯示多個影象

import matplotlib.pyplot as plt
import numpy as np

# 多個figure
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

# 使用figure()函式重新申請一個figure物件
# 注意,每次呼叫figure的時候都會重新申請一個figure物件
plt.figure()
# 第一個是橫座標的值,第二個是縱座標的值
plt.plot(x, y1)

# 第一個引數表示的是編號,第二個表示的是圖表的長寬
plt.figure(num = 3, figsize=(8, 5)) # 當我們需要在畫板中繪製兩條線的時候,可以使用下面的方法: plt.plot(x, y2) plt.plot(x, y1, color='red', # 線顏色 linewidth=1.0, # 線寬 linestyle='--' # 線樣式 ) plt.show()

  這裡會顯示兩個影象:

這裡寫圖片描述
這裡寫圖片描述

去除邊框,指定軸的名稱

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50) y1 = 2*x + 1 y2 = 2**x + 1 # 請求一個新的figure物件 plt.figure() # 第一個是橫座標的值,第二個是縱座標的值 plt.plot(x, y1) # 設定軸線的lable(標籤) plt.xlabel("I am x") plt.ylabel("I am y") plt.show()

這裡寫圖片描述

同時繪製多條曲線

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1
# num表示的是編號,figsize表示的是圖表的長寬
plt.figure(num = 3, figsize=(8, 5))  
plt.plot(x, y2)
# 設定線條的樣式
plt.plot(x, y1, 
         color='red',  # 線條的顏色
         linewidth=1.0,  # 線條的粗細
         linestyle='--'  # 線條的樣式
        )

# 設定取值引數範圍
plt.xlim((-1, 2))  # x引數範圍
plt.ylim((1, 3))  # y引數範圍

# 設定點的位置
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
# 為點的位置設定對應的文字。
# 第一個引數是點的位置,第二個引數是點的文字提示。
plt.yticks([-2, -1.8, -1, 1.22, 3],
          [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])

# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 繫結x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

plt.show()

這裡寫圖片描述

多條曲線之曲線說明

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

# 第一個引數表示的是編號,第二個表示的是圖表的長寬
plt.figure(num = 3, figsize=(8, 5))  
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# 設定取值引數
plt.xlim((-1, 2))
plt.ylim((1, 3))

# 設定lable
plt.xlabel("I am x")
plt.ylabel("I am y")

# 設定點的位置
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22,3],
          [r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$readly\ good$'])


l1, = plt.plot(x, y2, 
               label='aaa'
              )
l2, = plt.plot(x, y1, 
               color='red',  # 線條顏色
               linewidth = 1.0,  # 線條寬度
               linestyle='-.',  # 線條樣式
               label='bbb'  #標籤
              )

# 使用legend繪製多條曲線
plt.legend(handles=[l1, l2], 
           labels = ['aaa', 'bbb'], 
           loc = 'best'
          )

plt.show()

這裡寫圖片描述

多個figure,並加上特殊點註釋

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50)
y1 = 2*x + 1
y2 = 2**x + 1

plt.figure(figsize=(12, 8))  # 第一個引數表示的是編號,第二個表示的是圖表的長寬
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')

# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 繫結x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

# 顯示交叉點
x0 = 1
y0 = 2*x0 + 1
# s表示點的大小,預設rcParams['lines.markersize']**2
plt.scatter(x0, y0, s = 66, color = 'b')
# 定義線的範圍,X的範圍是定值,y的範圍是從y0到0的位置
# lw的意思是linewidth,線寬
plt.plot([x0, x0], [y0, 0], 'k-.', lw= 2.5)

# 設定關鍵位置的提示資訊
plt.annotate(r'$2x+1=%s$' % 
             y0, 
             xy=(x0, y0), 
             xycoords='data',

             xytext=(+30, -30),
             textcoords='offset points',
             fontsize=16,  # 這裡設定的是字型的大小
             # 這裡設定的是箭頭和箭頭的弧度
             arrowprops=dict(arrowstyle='->',connectionstyle='arc3,rad=.2')
            )

# 在figure中顯示文字資訊
# 可以使用\來輸出特殊的字元\mu\ \sigma\ \alpha
plt.text(0, 3, 
         r'$This\ is\ a\ good\ idea.\ \mu\ \sigma_i\ \alpha_t$',
         fontdict={'size':16,'color':'r'})

plt.show()

這裡寫圖片描述

tick能見度設定

import matplotlib.pyplot as plt
import numpy as np

# 從[-1,1]中等距去50個數作為x的取值
x = np.linspace(-1, 1, 50)
y = 2*x - 1

plt.figure(figsize=(12, 8))  # 第一個引數表示的是編號,第二個表示的是圖表的長寬
# alpha是設定透明度的
plt.plot(x, y, color='r', linewidth=10.0, alpha=0.5)

# gca = 'get current axis'
ax = plt.gca()
# 將右邊和上邊的邊框(脊)的顏色去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 繫結x軸和y軸
ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')
# 定義x軸和y軸的位置
ax.spines['bottom'].set_position(('data', 0))
ax.spines['left'].set_position(('data', 0))

# 可以使用tick設定透明度
for label in ax.get_xticklabels() + ax.get_yticklabels():
    label.set_fontsize(12)
    label.set_bbox(dict(facecolor='y', edgecolor='None', alpha=0.7))

plt.show()

這裡寫圖片描述

散點圖

import matplotlib.pyplot as plt
import numpy as np

n = 1024
# 從[0]
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(X, Y)

plt.scatter(np.arange(5), np.arange(5))

plt.xticks(())
plt.yticks(())

plt.show()

這裡寫圖片描述

條形圖

import matplotlib.pyplot as plt
import numpy as np

n = 12
X = np.arange(n)
Y1 = (1 - X/float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X/float(n)) * np.random.uniform(0.5, 1.0, n)

plt.figure(figsize=(12, 8))
plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')

for x, y in zip(X,Y1):
    # ha: horizontal alignment水平方向
    # va: vertical alignment垂直方向
    plt.text(x, y+0.05, '%.2f' % y, ha='center', va='bottom')

for x, y in zip(X,-Y2):
    # ha: horizontal alignment水平方向
    # va: vertical alignment垂直方向
    plt.text(x, y-0.05, '%.2f' % y, ha='center', va='top')

# 定義範圍和標籤
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())

plt.show()

這裡寫圖片描述

contour等高線圖

import matplotlib.pyplot as plt
import numpy as np

def get_height(x, y):
    # the height function
    return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)

n = 256
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X, Y = np.meshgrid(x, y)

plt.figure(figsize=(14, 8))

# use plt.contourf to filling contours
# X, Y and value for (X, Y) point

# 橫座標、縱座標、高度、 、透明度、cmap是顏色對應表
# 等高線的填充顏色
plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot)  

# use plt.contour to add contour lines
# 這裡是等高線的線
C = plt.contour(X, Y, get_height(X, Y), 16, color='black', linewidth=.5)

# adding label
plt.clabel(C, inline=True, fontsize=16)

plt.xticks(())
plt.yticks(())
plt.show()

這裡寫圖片描述

image圖片顯示

import matplotlib.pyplot as plt
import numpy as np

# image data
a = np.array([0.313660827978, 0.365348418405, 0.423733120134,
              0.365348418405, 0.439599930621, 0.525083754405,
              0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)

"""
for the value of "interpolation", check this:
http://matplotlib.org/examples/images_contours_and_fields/interpolation_methods.html
for the value of "origin"= ['upper', 'lower'], check this:
http://matplotlib.org/examples/pylab_examples/image_origin.html
"""

# 這是顏色的標註
# 主要使用imshow來顯示圖片,這裡暫時不適用圖片來顯示,採用色塊的方式演示。
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.90)  # 這是顏色深度的標註,shrink表示壓縮比例

plt.xticks(())
plt.yticks(())
plt.show()

這裡寫圖片描述

3D資料圖

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D

fig = plt.figure(figsize=(12, 8))
ax = Axes3D(fig)

# 生成X,Y
X = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X,Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)

# height value
Z = np.sin(R)

# 繪圖
# rstride(row)和cstride(column)表示的是行列的跨度
ax.plot_surface(X, Y, Z, 
                rstride=1,  # 行的跨度
                cstride=1,  # 列的跨度
                cmap=plt.get_cmap('rainbow')  # 顏色對映樣式設定
               )

# offset 表示距離zdir的軸距離
ax.contourf(X, Y, Z, zdir='z', offest=-2, cmap='rainbow')
ax.set_zlim(-2, 2)

plt.show()

這裡寫圖片描述

Subplot多合一顯示

import matplotlib.pyplot as plt
import numpy as np

plt.figure()

# 將整個figure分成兩行兩列
plt.subplot(2, 2, 1)
# 第一個引數表示X的範圍,第二個是y的範圍
plt.plot([0, 1], [0, 1])

plt.subplot(222)
plt.plot([0, 1], [0, 2])

plt.subplot(223)
plt.plot([0, 1], [0, 3])

plt.subplot(224)
plt.plot([0, 1], [0, 4])

plt.show()

這裡寫圖片描述

分格顯示

subplot2grid

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.gridspec as gridspec

plt.figure()
# 第一個元素表示將總的面板進行劃分,劃分為3行3列,
# 第二個元素表示該面板從0行0列開始,列的跨度(colspan)為3列,行的跨度(rowspan)為1
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1)
# 第一個元素的表示X的範圍為[1,2],第二個元素表示Y的範圍為[1,2]
ax1.plot([1, 2], [1, 2])
ax1.set_title(r'$ax1\_title$')
# 第一個元素表示將總的面板進行劃分,劃分為3行3列,
# 第二個元素表示該面板從1行0列開始,列的跨度(colspan)為2列,行的跨度(rowspan)取預設值1
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2)
ax2.set_title(r'$ax2\_title$')
# 第一個元素表示將總的面板進行劃分,劃分為3行3列,
# 第二個元素表示該面板從1行2列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取預設值1
ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
ax3.set_title(r'$ax3\_title$')
# 第一個元素表示將總的面板進行劃分,劃分為3行3列,
# 第二個元素表示該面板從2行0列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取預設值1
ax4 = plt.subplot2grid((3, 3), (2, 0))
ax4.set_title(r'$ax4\_title$')
# 第一個元素表示將總的面板進行劃分,劃分為3行3列,
# 第二個元素表示該面板從2行1列開始,行的跨度(rowspan)為2列,列的跨度(colspan)取預設值1
ax5 = plt.subplot2grid((3, 3), (2, 1))
ax5.set_title(r'$ax5\_title$')

plt.tight_layout()
plt.show()

這裡寫圖片描述

gridspec

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
# 首先,定義網格的佈局為3行3列
gs = gridspec.GridSpec(3, 3)
# 這裡表示從0行全部都是ax1的
ax1 = plt.subplot(gs[0, :])
ax1.set_title(r'$ax1\_title$')

# 這裡表示第一行中0列和1列都是ax2的
ax2 = plt.subplot(gs[1, :2])
ax2.set_title(r'$ax2\_title$')

# 這裡表示第一行中2列是ax3的
ax3 = plt.subplot(gs[1:, 2])
ax3.set_title(r'$ax3\_title$')

# 這裡表示最後一行中0列是ax4的
ax4 = plt.subplot(gs[-1, 0])
ax4.set_title(r'$ax4\_title$')

# 這裡表示最後一行中倒數第二列是ax5的
ax5 = plt.subplot(gs[-1, -2])
ax5.set_title(r'$ax5\_title$')

plt.tight_layout()
plt.show()

這裡寫圖片描述

easy to define structure分格顯示

import matplotlib.pyplot as plt
import numpy as np

plt.figure()
# sharex表示共享X軸,sharey表示共享y軸
f, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True)
# 顯示點(1, 2), (1, 2)
ax11.scatter([1, 2], [1, 2])

ax11.set_title('11')
ax12.set_title('11')
ax21.set_title('21')
ax22.set_title('22')

plt.tight_layout()
plt.show()

這裡寫圖片描述

圖中圖

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize=(10, 6))
x = [1, 2, 3, 4, 5, 6, 7]
y = [1, 3, 4, 2, 5, 8, 6]

# 大圖
left, bottom, width, weight = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, weight])
ax1.plot(x, y, 'r')
ax1.set_xlabel(r'$x$')
ax1.set_ylabel(r'$y$')
ax1.set_title(r'$××Interesting××$')

# 左上小圖
left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, weight])
ax2.plot(y, x, 'b')
ax2.set_xlabel(r'$x$')
ax2.set_ylabel(r'$y$')
ax2.set_title(r'$title\ inside\ 1$')

# 右下小圖
plt.axes([0.6, 0.2, 0.25, 0.25])
# 將y的資料逆序輸出[::1]
plt.plot(y[::-1],x, 'g')
plt.xlabel('x')
plt.ylabel('y')
plt.title(r'$title\ inside\ 2$')

plt.show()

這裡寫圖片描述

主次座標軸

import matplotlib.pyplot as plt
import numpy as np

# 從[0, 10]以0.1為間隔,形成一個列表
x = np.arange(0, 10, 0.1)
y1 = 0.05 * x**2
y2 = -1 * y1


fig, ax1 = plt.subplots()
# 映象(上下左右顛倒)
ax2 = ax1.twinx()
ax1.plot(x, y1, 'g-')
ax2.plot(x, y2, 'b--')

# 為軸進行命名
ax1.set_xlabel(r'$X\ data$', fontsize=16)
ax1.set_ylabel(r'$Y1$', color='g', fontsize=16)
ax2.set_ylabel(r'$Y2$', color='b', fontsize=16)

plt.show()

這裡寫圖片描述

Animation動畫

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation

fig, ax = plt.subplots()

# 從[0, 2*np.pi]以0.01為間隔,形成一個列表
x = np.arange(0, 2*np.pi, 0.01)
# 這裡只需要列表的第一個元素,所以就用逗號“,”加空白的形式省略了列表後面的元素
line, = ax.plot(x, np.sin(x))

def animate(i):
    line.set_ydata(np.sin(x + i/100))
    return line, 

def init():
    line.set_ydata(np.sin(x))
    # 這裡由於僅僅需要列表的第一個引數,所以後面的就直接用空白省略了
    return line,  

ani = animation.FuncAnimation(fig=fig, 
                              func=animate,  # 動畫函式
                              frames=100,   # 幀數
                              init_func=init,  # 初始化函式
                              interval=20,  # 20ms
                              blit=True)

plt.show()

這裡寫圖片描述