您好,登錄后才能下訂單哦!
Matplotlib是 Python 2D-繪圖領(lǐng)域使用最廣泛的套件,可以簡(jiǎn)易地將數(shù)據(jù)圖形化,并且提供多樣化的輸出格式。
matplotlib有兩個(gè)接口,一個(gè)是狀態(tài)機(jī)層的接口,通過pyplot模塊來進(jìn)行管理;一個(gè)是面向?qū)ο蟮慕涌?,通過pylab模塊將所有的功能函數(shù)全部導(dǎo)入其單獨(dú)的命名空間內(nèi)。
使用conda安裝如下:conda install matplotlib
Matplotlib基本圖表結(jié)構(gòu)包括坐標(biāo)軸(X軸、Y軸)、坐標(biāo)軸標(biāo)簽(axisLabel)、
坐標(biāo)軸刻度(tick)、坐標(biāo)軸刻度標(biāo)簽(tick label)、繪圖區(qū)(axes)、畫布(figure)。
Figure代表一個(gè)繪制面板,其中可以包涵多個(gè)Axes(即多個(gè)圖表)。
Axes表示一個(gè)圖表?,一個(gè)Axes包涵:titlek、xaxis、yaxis。
為了支持pylab中的gca()等函數(shù),F(xiàn)igure對(duì)象內(nèi)部保存有當(dāng)前軸的信息,因此不建議直接對(duì)Figure.axes屬性進(jìn)行列表操作,而應(yīng)該使用add_subplot, add_axes, delaxes等方法進(jìn)行添加和刪除操作。
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
fig = plt.figure()
ax1 = fig.add_axes([0.1, 0.45, 0.8, 0.5])
ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.2])
x1 = np.linspace(0.0, 5.0)
x2 = np.linspace(0.0, 3.0)
y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
y2 = np.cos(2 * np.pi * x2)
ax1.patch.set_facecolor("green")
ax1.grid(True)
line1 = ax1.plot(x1, y1, 'yo-')
line2 = ax2.plot(x2, y2, 'r.-')
plt.show()
網(wǎng)格線設(shè)置plt.grid(color='r',linestyle='-.')
axis:坐標(biāo)軸,可選值為x,y
color:支持十六進(jìn)制顏色
linestyle: –,-.,:
alpha:透明度,0——1
坐標(biāo)軸范圍設(shè)置plt.axis([xmin,xmax,ymin,ymax])
也可以通過xlim(xmin,xmax),ylim(xmin,xmax)方法設(shè)置坐標(biāo)軸范圍
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.arange(-10, 10, 0.1)
y = x ** 2
plt.plot(x, y,)
plt.axis([-10, 10, 0, 100])
plt.show()
關(guān)閉坐標(biāo)軸plt.axis('off')
設(shè)置畫布比例plt.figure(figsize=(a,b))
a是x軸刻度比例,b是y軸刻度比例。
圖例設(shè)置有兩種方法,一種是分別在plot函數(shù)中使用label參數(shù)指定,再調(diào)用plt.legend()方法顯示圖例;一種是直接在legend方法中傳入字符串列表設(shè)置圖例。
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.arange(-10, 10, 0.1)
y = x ** 2
plt.plot(x, y, label='y = x ** 2')
plt.legend()
plt.show()
使用legend函數(shù)設(shè)置圖例時(shí),參數(shù)如下:
圖例名稱列表:傳遞的圖例名稱列表必須與曲線繪制順序一致。
loc:用于設(shè)置圖例標(biāo)簽的位置,matplotlib預(yù)定義了多種數(shù)字表示的位置。
best:0,upper right:1,upper left:2,lower left:3,lower right:4,right:5,center left:6,center right:7,lower center:8,upper center:9,center:10,loc參數(shù)可以是2個(gè)元素的元組,表示圖例左下角的坐標(biāo),[0,0] 左下,[0,1] 左上,[1,0] 右下,[1,1] 右上。
ncol:圖例的列數(shù)
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x1 = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x1)
plt.plot(x1, y1)
x2 = x1 = np.linspace(0, 2 * np.pi, 100)
y2 = np.cos(x1)
plt.plot(x2, y2)
plt.legend(['sin(x)', 'cos(x)'], loc=0, ncol=1)
plt.show()
標(biāo)題設(shè)置可以使用plt.title()方法或ax.set_title()方法。
拋物線繪制:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.arange(-10, 10, 0.1)
y = x ** 2
plt.plot(x, y)
plt.show()
正弦曲線繪制:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
plt.plot(x, y)
plt.show()
多條曲線繪制:
多次調(diào)用plot函數(shù)可以在圖上繪制多條曲線。
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x1 = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x1)
plt.plot(x1, y1)
x2 = x1 = np.linspace(0, 2 * np.pi, 100)
y2 = np.cos(x1)
plt.plot(x2, y2)
plt.show()
可以在一個(gè)plot函數(shù)中傳入多對(duì)X,Y值,在一個(gè)圖中繪制多個(gè)曲線。
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x1 = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x1)
x2 = x1 = np.linspace(0, 2 * np.pi, 100)
y2 = np.cos(x1)
plt.plot(x1, y1, x2, y2)
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = np.random.randint(0, 100, 100)
bins = np.arange(0, 101, 10)
fig = plt.figure(figsize=(12, 6))
plt.subplot(1, 1, 1)
plt.hist(x, bins, color='b', alpha=0.6)
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
fig = plt.figure(figsize=(12, 6))
plt.subplot(1, 1, 1)
plt.plot(x, y, color='r', linestyle='-')
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x = [1, 2, 3, 4, 5]
y = [2.3, 3.4, 1.2, 6.6, 7.0]
plt.figure()
plt.bar(x, y)
plt.title("bar")
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
y = [2.3, 3.4, 1.2, 6.6, 7.0]
plt.figure()
plt.pie(y)
plt.title('PIE')
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
n = 1024
X = np.random.normal(0, 1, n)
Y = np.random.normal(0, 1, n)
T = np.arctan2(Y, X)
plt.axes([0.025, 0.025, 0.95, 0.95])
plt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5), plt.xticks([])
plt.ylim(-1.5, 1.5), plt.yticks([])
plt.show()
# -*- coding=utf-8 -*-
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)
if __name__ == "__main__":
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))
plt.contourf(X, Y, get_height(X, Y), 16, alpah=0.7, cmap=plt.cm.hot)
#
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()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
if __name__ == "__main__":
fig = plt.figure()
ax = Axes3D(fig)
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)
Z = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.hot)
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.cm.hot)
ax.set_zlim(-2, 2)
plt.show()
圖片加載顯示:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
if __name__ == "__main__":
img = plt.imread('network.png')
plt.imshow(img)
plt.show()
圖片保存:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
x1 = np.linspace(0, 2 * np.pi, 100)
y1 = np.sin(x1)
plt.plot(x1, y1)
x2 = x1 = np.linspace(0, 2 * np.pi, 100)
y2 = np.cos(x1)
plt.plot(x2, y2)
plt.legend(['sin(x)', 'cos(x)'], loc=0, ncol=1)
plt.savefig('test.png')
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
# 創(chuàng)建一個(gè) 8 * 6 點(diǎn)(point)的圖,并設(shè)置分辨率為 80
plt.figure(figsize=(8, 6), dpi=80)
# 創(chuàng)建一個(gè)新的 1 * 1 的子圖,接下來的圖樣繪制在其中的第 1 塊(也是唯一的一塊)
plt.subplot(1, 1, 1)
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C, S = np.cos(X), np.sin(X)
# 繪制余弦曲線,使用藍(lán)色的、連續(xù)的、寬度為 1 (像素)的線條
plt.plot(X, C, color="blue", linewidth=2.5, line)
# 繪制正弦曲線,使用綠色的、連續(xù)的、寬度為 1 (像素)的線條
plt.plot(X, S, color="red", linewidth=2.5, line)
# 坐標(biāo)軸的范圍
xmin, xmax = X.min(), X.max()
ymin, ymax = C.min(), C.max()
# 計(jì)算坐標(biāo)軸的冗余
dx = (xmax - xmin) * 0.2
dy = (ymax - ymin) * 0.2
# 設(shè)置橫軸的上下限
plt.xlim(xmin - dx, xmax + dx)
# 設(shè)置縱軸的上下限
plt.ylim(ymin - dy, ymax + dy)
# 設(shè)置橫軸記號(hào)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
# 設(shè)置縱軸記號(hào)
plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'])
# 設(shè)置坐標(biāo)軸位置
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))
# 設(shè)置圖例
plt.plot(X, C, color="blue", linewidth=2.5, line, label="cosine")
plt.plot(X, S, color="red", linewidth=2.5, line, label="sine")
plt.legend(loc='upper left')
# 在2pi/3位置做標(biāo)注
t = 2 * np.pi / 3
plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, line)
plt.scatter([t, ], [np.cos(t), ], 50, color='blue')
plt.annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
xy=(t, np.sin(t)), xycoords='data',
xytext=(+10, +30), textcoords='offset points', fontsize=16,
arrowprops=dict(arrow, connection))
plt.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, line)
plt.scatter([t, ], [np.sin(t), ], 50, color='red')
plt.annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',
xy=(t, np.cos(t)), xycoords='data',
xytext=(-90, -50), textcoords='offset points', fontsize=16,
arrowprops=dict(arrow, connection))
# 坐標(biāo)軸刻度標(biāo)簽半透明化
for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(16)
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65))
plt.show()
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
if __name__ == "__main__":
fig = plt.figure(figsize=(10, 6))
fig.set_facecolor('white')
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
ax = fig.add_axes([left, bottom, width, weight])
ax.plot(x, y, 'r')
ax.set_xlabel(r'$X$')
ax.set_ylabel(r'$Y$')
ax.set_title(r'$BigFigure$')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 左上小圖
left, bottom, width, weight = 0.2, 0.6, 0.25, 0.25
ax1 = fig.add_axes([left, bottom, width, weight])
ax1.plot(y, x, 'b')
ax1.set_xlabel(r'$x$')
ax1.set_ylabel(r'$y$')
ax1.set_title(r'$figure1$')
ax1.spines['right'].set_color('none')
ax1.spines['top'].set_color('none')
plt.show()
可以直接使用Pandas的Series、DataFrame實(shí)例的plot直接進(jìn)行繪圖。
Series示例如下:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
if __name__ == "__main__":
# Series繪圖
x = np.linspace(0, 2 * np.pi, 100)
# 正弦曲線
y = np.sin(x)
s = pd.Series(data=y, index=x)
s.plot()
plt.show()
DataFrame實(shí)例:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
if __name__ == "__main__":
# DataFrame繪圖
x = np.linspace(0, 2 * np.pi, 100)
df = pd.DataFrame(data={'sin': np.sin(x), 'cos': np.cos(x)}, index=x)
df.plot()
# 取出某列數(shù)據(jù)進(jìn)行繪圖
# df['sin'].plot()
plt.show()
DataFrame繪制柱狀圖:
# -*- coding=utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
if __name__ == "__main__":
df = pd.DataFrame(np.random.randint(0, 10, size=(8, 4)), index=list('abcdefgh'), columns=list('ABCD'))
ax = df.plot(kind='bar')
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
kind='barh'參數(shù)表示繪制水平柱狀圖。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。