您好,登錄后才能下訂單哦!
Matplotlib是 Python 2D-繪圖領域使用最廣泛的套件,可以簡易地將數據圖形化,并且提供多樣化的輸出格式。
matplotlib有兩個接口,一個是狀態機層的接口,通過pyplot模塊來進行管理;一個是面向對象的接口,通過pylab模塊將所有的功能函數全部導入其單獨的命名空間內。
使用conda安裝如下:conda install matplotlib
Matplotlib基本圖表結構包括坐標軸(X軸、Y軸)、坐標軸標簽(axisLabel)、
坐標軸刻度(tick)、坐標軸刻度標簽(tick label)、繪圖區(axes)、畫布(figure)。
Figure代表一個繪制面板,其中可以包涵多個Axes(即多個圖表)。
Axes表示一個圖表?,一個Axes包涵:titlek、xaxis、yaxis。
為了支持pylab中的gca()等函數,Figure對象內部保存有當前軸的信息,因此不建議直接對Figure.axes屬性進行列表操作,而應該使用add_subplot, add_axes, delaxes等方法進行添加和刪除操作。
# -*- 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()
網格線設置plt.grid(color='r',linestyle='-.')
axis:坐標軸,可選值為x,y
color:支持十六進制顏色
linestyle: –,-.,:
alpha:透明度,0——1
坐標軸范圍設置plt.axis([xmin,xmax,ymin,ymax])
也可以通過xlim(xmin,xmax),ylim(xmin,xmax)方法設置坐標軸范圍
# -*- 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()
關閉坐標軸plt.axis('off')
設置畫布比例plt.figure(figsize=(a,b))
a是x軸刻度比例,b是y軸刻度比例。
圖例設置有兩種方法,一種是分別在plot函數中使用label參數指定,再調用plt.legend()方法顯示圖例;一種是直接在legend方法中傳入字符串列表設置圖例。
# -*- 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函數設置圖例時,參數如下:
圖例名稱列表:傳遞的圖例名稱列表必須與曲線繪制順序一致。
loc:用于設置圖例標簽的位置,matplotlib預定義了多種數字表示的位置。
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參數可以是2個元素的元組,表示圖例左下角的坐標,[0,0] 左下,[0,1] 左上,[1,0] 右下,[1,1] 右上。
ncol:圖例的列數
# -*- 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()
標題設置可以使用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()
多條曲線繪制:
多次調用plot函數可以在圖上繪制多條曲線。
# -*- 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()
可以在一個plot函數中傳入多對X,Y值,在一個圖中繪制多個曲線。
# -*- 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__":
# 創建一個 8 * 6 點(point)的圖,并設置分辨率為 80
plt.figure(figsize=(8, 6), dpi=80)
# 創建一個新的 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)
# 繪制余弦曲線,使用藍色的、連續的、寬度為 1 (像素)的線條
plt.plot(X, C, color="blue", linewidth=2.5, line)
# 繪制正弦曲線,使用綠色的、連續的、寬度為 1 (像素)的線條
plt.plot(X, S, color="red", linewidth=2.5, line)
# 坐標軸的范圍
xmin, xmax = X.min(), X.max()
ymin, ymax = C.min(), C.max()
# 計算坐標軸的冗余
dx = (xmax - xmin) * 0.2
dy = (ymax - ymin) * 0.2
# 設置橫軸的上下限
plt.xlim(xmin - dx, xmax + dx)
# 設置縱軸的上下限
plt.ylim(ymin - dy, ymax + dy)
# 設置橫軸記號
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$'])
# 設置縱軸記號
plt.yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$'])
# 設置坐標軸位置
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))
# 設置圖例
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位置做標注
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))
# 坐標軸刻度標簽半透明化
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實例的plot直接進行繪圖。
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實例:
# -*- 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()
# 取出某列數據進行繪圖
# 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'參數表示繪制水平柱狀圖。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。