1. 程式人生 > >python matplotlib 畫圖簡介

python matplotlib 畫圖簡介

python的matplotlib包支援我們畫圖,有點非常多,現學習如下。

首先要匯入包,在以後的示例中預設已經匯入這兩個包

import matplotlib.pyplot as plt
import numpy as np
然後畫一個最基本的圖
t = np.arange(0.0, 2.0, 0.01)#x軸上的點,0到2之間以0.01為間隔
s = np.sin(2*np.pi*t)#y軸為正弦
plt.plot(t, s)#畫圖

plt.xlabel('time (s)')#x軸標籤
plt.ylabel('voltage (mV)')#y軸標籤
plt.title('About as simple as it gets, folks')#圖的標籤
plt.grid(True)#產生網格
plt.savefig("test.png")#儲存影象
plt.show()#顯示影象
這是在一個視窗中畫單張圖的過程,那麼如何畫多張圖呢?畫圖的過程相同,無非是畫多張,然後設定位置。
x1 = np.linspace(0.0, 5.0)#畫圖一
x2 = np.linspace(0.0, 2.0)#畫圖二
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)

plt.subplot(2, 1, 1)#面板設定成2行1列,並取第一個(順時針編號)
plt.plot(x1, y1, 'yo-')#畫圖,染色
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)#面板設定成2行1列,並取第二個(順時針編號)
plt.plot(x2, y2, 'r.-')#畫圖,染色
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()

兩張圖的示例如下


直方圖的畫法

# -*- coding:utf-8 -*-
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt

mu = 100  # 正態分佈的均值
sigma = 15  # 標準差
x = mu + sigma * np.random.randn(10000)#在均值周圍產生符合正態分佈的x值

num_bins = 50
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='green', alpha=0.5)
#直方圖函式,x為x軸的值,normed=1表示為概率密度,即和為一,綠色方塊,色深引數0.5.返回n個概率,直方塊左邊線的x值,及各個方塊物件
y = mlab.normpdf(bins, mu, sigma)#畫一條逼近的曲線
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')#中文標題 u'xxx'

plt.subplots_adjust(left=0.15)#左邊距
plt.show()

直方圖如下

3D影象的畫法

3D離散點

<span style="font-size:12px;">#!/usr/bin/env python
# encoding: utf-8

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

x_list = [[3,3,2],[4,3,1],[1,2,3],[1,1,2],[2,1,2]]
fig = plt.figure()
ax = fig.gca(projection='3d')
for x in x_list:
    ax.scatter(x[0],x[1],x[2],c='r')
plt.show()</span>

畫空間平面

from mpl_toolkits.mplot3d.axes3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
  
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
X=np.arange(1,10,1)
Y=np.arange(1,10,1)
X, Y = np.meshgrid(X, Y)
Z = 3*X+2*Y+30
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,cmap=cm.jet,linewidth=0, antialiased=True)
ax.set_zlim3d(0,100)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show() 

畫空間曲面

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5, 5, 0.1)
Y = np.arange(-5, 5, 0.1)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
#畫表面,x,y,z座標, 橫向步長,縱向步長,顏色,線寬,是否漸變
ax.set_zlim(-1.01, 1.01)#座標系的下邊界和上邊界

ax.zaxis.set_major_locator(LinearLocator(10))#設定Z軸標度
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))#Z軸精度
fig.colorbar(surf, shrink=0.5, aspect=5)#shrink顏色條伸縮比例(0-1),aspect顏色條寬度(反比例,數值越大寬度越窄)

plt.show()

3D圖分別如下

餅狀圖畫法

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'#設定標籤
sizes = [15, 30, 45, 10]#佔比,和為100
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']#顏色
explode = (0, 0.1, 0, 0)  #展開第二個扇形,即Hogs,間距為0.1

plt.pie(sizes, explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90)#startangle控制餅狀圖的旋轉方向
plt.axis('equal')#保證餅狀圖是正圓,否則會有一點角度偏斜

fig = plt.figure()
ax = fig.gca()

import numpy as np

ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90, radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors, autopct='%1.1f%%', shadow=True, startangle=90,radius=0.25, center=(1, 0), frame=True)

ax.set_xticks([0, 1])#設定位置
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"])#設定標籤
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5))
ax.set_ylim((-0.5, 1.5))

ax.set_aspect('equal')
plt.show()
餅狀圖如下: