日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

一文了解python作图(matplotlib.pyplot)

發布時間:2024/1/18 python 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 一文了解python作图(matplotlib.pyplot) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

參考視頻:為什么用 Matplotlib

視頻總時長兩個多小時,可以整體看一遍,然后看這個就會很清楚

文章目錄

  • 1. 基本用法
    • 1.1 基礎作圖
    • 1.2 figure圖像
    • 1.3 設置坐標軸
      • 1.3.1 基本設置
      • 1.3.2 使用Latex公式
      • 1.3.3 設置坐標軸位置
    • 1.4 legend圖例
      • 1.4.1 基礎使用
      • 1.4.2 設置圖例位置
      • 1.4.3 指定顯示某幾條線并設置新名稱
    • 1.5 annotation 注解
    • 1.6 設置tick可見度
  • 2 數據呈現
    • 2.1 散點圖
    • 2.2 條形圖
    • 2.3 等高線圖
    • 2.4 使用圖片
    • 2.5 3D數據
  • 3. Subplot多合一顯示
    • 3.1 plt.subplot
    • 3.2 plt.subplot2grid
    • 3.3 gridspec.GridSpec
    • 3.4 plt.subplots
  • 4. 其他
    • 4.1 圖中圖
    • 4.2 次坐標軸
    • 4.3 動畫 animation

1. 基本用法

1.1 基礎作圖

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-1, 1, 50) y = x * x + 1 plt.plot(x, y) plt.show()

1.2 figure圖像

在不同的figure中展示不同的圖片,在每次繪圖前指定plt.figure()即可繪制到不同figure中,其中可以指定figure的序號

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-1, 1, 50) y1 = x * x + 1 y2 = 2 * xplt.figure(num=1) plt.plot(x, y1)plt.figure(num=2, figsize=(8, 5)) plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--') plt.show()

figure1:

figure2:

1.3 設置坐標軸

1.3.1 基本設置

  • plt.xlim(xleft, xright):設置x軸顯示范圍
  • plt.ylim(ylow, yhigh):設置y軸的顯示范圍
  • plt.xlabel(description):設置x軸描述
  • plt.ylabel(description):設置y軸描述
  • plt.xticks([1,2,3,4,5]):設置x軸標簽
  • plt.yticks([1,2,3,4,5]):設置y軸標簽
  • plt.yticks([1,2,3], ['one','two','three]):設置對應標簽位置文字
  • plt.xlabel(r'$axis x description \alpha$'):使用latex公式
import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * xplt.figure(num=2, figsize=(8, 5)) plt.plot(x, y2) plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--')# 設置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim(-2, 3)# 設置x,y軸的坐標軸描述 plt.xlabel('axis x description') plt.ylabel('axis y description')# 設置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', 'good', 'really god'])plt.show()

1.3.2 使用Latex公式

其中文字部分也可以使用latex公式進行描述,例如設置某個label為 g o o d β good\ \beta good?β

# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])

1.3.3 設置坐標軸位置

首先去掉右邊和上邊兩個邊框,然后設置x軸為下邊框,y軸為上邊框,最后設置邊框位置即可

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * xplt.plot(x, y2) plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--')# 設置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設置x,y軸的坐標軸描述 plt.xlabel(r'$axis x description$', loc="right") plt.ylabel('axis y description', loc='top')# 設置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])# gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))plt.show()

1.4 legend圖例

1.4.1 基礎使用

通過給每一個plot出來的圖像添加label屬性,然后調用plt.legend()即可顯示圖例

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設置x,y軸的坐標軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])plt.plot(x, y2, label='up') plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend()plt.show()

1.4.2 設置圖例位置

支持的位置屬性:'best', 'upper right', 'upper left', 'lower left', 'lower right', 'right', 'center left', 'center right', 'lower center', 'upper center', 'center'

best是根據線的顯示位置尋找最優的顯示地方

通過調用plt.legend(loc='')指定loc屬性即可

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設置x,y軸的坐標軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])plt.plot(x, y2, label='up') plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend(loc="upper right")plt.show()

1.4.3 指定顯示某幾條線并設置新名稱

雖然繪制了兩條線,但是通過handles屬性可以指定繪制某幾條線,同時也可以設置各線的先后位置,另外還可以通過labels指定新的圖例名稱

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = x * x + 1 y2 = 2 * x# 設置x,y軸的顯示范圍 plt.xlim(-1, 2) plt.ylim((-2, 3))# 設置x,y軸的坐標軸描述 plt.xlabel(r'$axis x description$') plt.ylabel('axis y description')# 設置分度值 new_ticks = np.linspace(-1, 2, 5) plt.xticks(new_ticks)# 設置為中文 plt.yticks([-2, -1.5, 0, 1, 3],['really bad', 'bad', 'normal', r'$good\ \beta$', 'really god'])l1, = plt.plot(x, y2, label='up') l2, = plt.plot(x, y1, color='red', linewidth='1.0', linestyle='--', label='down') plt.legend(handles=[l1], labels=['aaa'], loc="upper right")plt.show()

1.5 annotation 注解

通過plt.annotation()和plt.text()為圖象添加注解

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y1 = 2 * x + 1plt.figure(figsize=(8, 5)) plt.plot(x, y1)# gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))x0 = 1 y0 = 2 * x0 + 1 plt.scatter(x0, y0, s=50, color='b') plt.plot([x0, x0], [0, y0], 'k--', linewidth=2)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'))plt.text(-3, 3, r"$This\ is\ annotation.\ \mu\ \sigma_i $", fontdict={'size': 16, "color": 'r'}) plt.show()

1.6 設置tick可見度

有時候線會把標簽壓住,此時可以通過設置標簽的zorder屬性來制定覆蓋順序

zorder用來控制繪圖的順序,也就是所謂的疊加樣式。zorder越大,相當于畫上去的越晚,也就在上面了。

import matplotlib.pyplot as plt import numpy as npx = np.linspace(-3, 3, 50) y2 = 0.1 * xplt.plot(x, y2, linewidth=10, zorder=1) plt.ylim(-2, 2) # gca: get current axis ax = plt.gca() ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ax.xaxis.set_ticks_position('bottom') ax.yaxis.set_ticks_position('left') ax.spines['bottom'].set_position(('data', 0)) ax.spines['left'].set_position(('data', 0))for label in ax.get_xticklabels() + ax.get_yticklabels():label.set_zorder(2)label.set_fontsize(12)label.set_bbox(dict(facecolor='white',edgecolor='None',alpha=0.7))plt.show()

2 數據呈現

2.1 散點圖

通過plt.scatter()生成散點圖

import matplotlib.pyplot as plt import numpy as npn = 1024X = np.random.normal(0, 1, n) Y = np.random.normal(0, 1, n) T = np.arctan2(Y, X)plt.scatter(X, Y, s=75, c=T, alpha=.5)plt.xlim(-1.5, 1.5) plt.ylim(-1.5, 1.5)plt.xticks([]) plt.yticks([]) plt.show()

生成一條斜線散點圖

import matplotlib.pyplot as plt import numpy as npplt.scatter(np.arange(5), np.arange(5))plt.show()

2.2 條形圖

使用plt.bar()繪制條形圖

import matplotlib.pyplot as plt import numpy as npn = 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.bar(X, +Y1, facecolor='#9999ff', edgecolor='white') plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')for x, y in zip(X, Y1):# ha: horizontal alignmentplt.text(x, y + 0.05, '%.2f' % y, ha='center', va='bottom')for x, y in zip(X, Y2):# ha: horizontal alignmentplt.text(x, -y - 0.05, '%.2f' % y, ha='center', va='top')plt.xlim(-0.5, n) plt.xticks([]) plt.ylim(-1.25, 1.25) plt.yticks([])plt.show()

2.3 等高線圖

  • 使用plt.meshgrid()生成框格
  • 使用plt.contourf()生成等高線填充圖
  • 使用plt.contour()生成等高線
import matplotlib.pyplot as plt import numpy as npdef f(x, y):# 高度計算公式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.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=plt.cm.hot)# 設置等高線 C = plt.contour(X, Y, f(X, Y), 8, colors='black')# 添加高度標簽 plt.clabel(C, inline=True, fontsize=10) plt.xticks([]) plt.yticks([]) plt.show()

2.4 使用圖片

import matplotlib.pyplot as plt import numpy as npimg = np.random.uniform(0, 1000, 100).reshape((10, 10))plt.imshow(img, interpolation='nearest', origin='upper') plt.colorbar()plt.xticks([]) plt.yticks([]) plt.show()

2.5 3D數據

import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D# 生成3D figure fig = plt.figure() ax = Axes3D(fig, auto_add_to_figure=False) fig.add_axes(ax)# X, Y value 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.get_cmap('rainbow'), edgecolor='k') ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow')ax.set_zlim(-2, 2) plt.show()

3. Subplot多合一顯示

3.1 plt.subplot

使用plt.subplot(rownum, columnnum, index)說明新圖紙是幾行幾列的

import matplotlib.pyplot as pltplt.figure() plt.subplot(2, 2, 1) plt.plot([0, 1], [0, 1])plt.subplot(2, 2, 2) plt.plot([0, 1], [0, 1])plt.subplot(2, 1, 2) plt.plot([0, 1], [0, 1])plt.show()

3.2 plt.subplot2grid

使用plt.subplot2grid(總格數, 起始格數, rowspan, colspan)來繪制

import matplotlib.pyplot as pltplt.figure() ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3, rowspan=1) ax1.plot([1, 2], [1, 2]) # 設置某屬性的時候需要在前面加set_ ax1.set_title("ax1 title")ax2 = plt.subplot2grid((3, 3), (1, 0), colspan=2) ax3 = plt.subplot2grid((3, 3), (1, 2), rowspan=2) ax4 = plt.subplot2grid((3, 3), (2, 0)) ax5 = plt.subplot2grid((3, 3), (2, 1))plt.tight_layout() plt.show()

3.3 gridspec.GridSpec

首先使用gridspec.GridSpec(rownum, colnum)聲明將figure分割成幾塊,然后在繪圖時使用切片聲明使用哪幾塊即可

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspecplt.figure() gs = gridspec.GridSpec(3, 3) ax1 = plt.subplot(gs[0, :]) ax2 = plt.subplot(gs[1, :2]) ax3 = plt.subplot(gs[1:, 2]) ax4 = plt.subplot(gs[2, 0]) ax5 = plt.subplot(gs[2, 1])plt.tight_layout() plt.show()

3.4 plt.subplots

import matplotlib.pyplot as plt import matplotlib.gridspec as gridspecf, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex=True, sharey=True) ax11.plot([1, 2], [1, 2])plt.tight_layout() plt.show()

4. 其他

4.1 圖中圖

通過指定在整個figure中的位置和大小來完成圖中圖的效果

  • 方法一:通過fig.add_axes([left, bottom, width, height])來生成新的axes繪制
  • 方法二:通過plt.axes([left, bottom, width, height])直接聲明接下來要繪制的圖形
import matplotlib.pyplot as pltfig = plt.figure() x = [1, 2, 3, 4, 5, 6, 7] y = [1, 3, 4, 2, 5, 8, 6]# 大圖 left, bottom, width, height = 0.1, 0.1, 0.8, 0.8 ax1 = fig.add_axes([left, bottom, width, height]) ax1.plot(x, y) ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_title('title')# 小圖 left, bottom, width, height = 0.2, 0.6, 0.25, 0.25 ax1 = fig.add_axes([left, bottom, width, height]) ax1.plot(y, x, 'b') ax1.set_xlabel('x') ax1.set_ylabel('y') ax1.set_title('inside 1')# 另一種方法 plt.axes([0.6, 0.2, 0.25, 0.25]) plt.plot(y[::-1], x, 'g') plt.xlabel('x') plt.ylabel('y') plt.title('inside 2')plt.show()

4.2 次坐標軸

在同一個圖中兩邊顯示不同的坐標軸對應不同的數據

import matplotlib.pyplot as plt import numpy as npx = np.arange(0, 10, 0.1) y1 = 0.05 * x ** 2 y2 = -1 * y1fig, ax1 = plt.subplots() ax2 = ax1.twinx()ax1.plot(x, y1, 'g-') ax2.plot(x, y2, 'b--')ax1.set_xlabel('X data') ax1.set_ylabel('Y1', color='g') ax2.set_ylabel('Y2', color='g')plt.show()

4.3 動畫 animation

import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animationfig, ax = plt.subplots()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 / 10))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, blit=True)plt.show()

總結

以上是生活随笔為你收集整理的一文了解python作图(matplotlib.pyplot)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。