Python、Matplot的subplot实现一行3列的子图绘制,并添加背景色
生活随笔
收集整理的這篇文章主要介紹了
Python、Matplot的subplot实现一行3列的子图绘制,并添加背景色
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python、Matplot的subplot實現一行3列的子圖繪制,并添加背景色
- 1. 可能遇到的問題
- 2. 示例
- 1)繪制2*2(倆行倆列)的子圖,并設置背景色
- 2) 繪制1*3(一行三列)的子圖,并設置橫軸縱軸值
- 3)繪制1*3(一行三列)的復雜子圖
- 4)將多個圖4*5(四行五列)顯示在一張圖像上
- 參考:
1. 可能遇到的問題
AttributeError: ‘AxesSubplot’ object has no property ‘axisbg’
問題描述:使用 Matplotlib subplot繪制2行2列的子圖,并帶有背景色時報如上錯誤
錯誤原因,subplot中沒有 axisbg 屬性
解決辦法:把axisbg 改成 facecolor
2. 示例
1)繪制2*2(倆行倆列)的子圖,并設置背景色
#!/usr/bin/env python
# !encoding=utf-8import matplotlib.pyplot as pltif __name__ == '__main__':for i, color in enumerate("rgby"):# 報錯:AttributeError: 'AxesSubplot' object has no property 'axisbg'# plt.subplot(221 + i, axisbg=color)# 成功plt.subplot(221 + i, facecolor=color)plt.show()
修改后成功如圖:
2) 繪制1*3(一行三列)的子圖,并設置橫軸縱軸值
#!/usr/bin/env python
# !encoding=utf-8import matplotlib.pyplot as plt
import numpy as npif __name__ == '__main__':for i, color in enumerate("rgb"):# 報錯:AttributeError: 'AxesSubplot' object has no property 'axesbg'# plt.subplot(221 + i, axesbg=color)# 成功plt.subplot(131 + i, facecolor=color)# x軸等差數列,y軸等比數列x = i + 1x1 = np.arange(0, x, 1)y1 = np.logspace(1, x, num=x, base=2)print(x1, ' ', y1)plt.plot(x1, y1)plt.show()
3)繪制1*3(一行三列)的復雜子圖
import numpy as np
import matplotlib.pyplot as plt# example data
x = np.arange(0.1, 4, 0.1)
y1 = np.exp(-1.0 * x)
y2 = np.exp(-0.5 * x)# example variable error bar values
y1err = 0.1 + 0.1 * np.sqrt(x)
y2err = 0.1 + 0.1 * np.sqrt(x / 2)# Now switch to a more OO interface to exercise more features.
fig, (ax_l, ax_c, ax_r) = plt.subplots(nrows=1, ncols=3,sharex=True, figsize=(12, 6))ax_l.set_title('all errorbars')
ax_l.errorbar(x, y1, yerr=y1err)
ax_l.errorbar(x, y2, yerr=y2err)ax_c.set_title('only every 6th errorbar')
ax_c.errorbar(x, y1, yerr=y1err, errorevery=6)
ax_c.errorbar(x, y2, yerr=y2err, errorevery=6)ax_r.set_title('second series shifted by 3')
ax_r.errorbar(x, y1, yerr=y1err, errorevery=4)
ax_r.errorbar(x, y2, yerr=y2err, errorevery=3)fig.suptitle('Errorbar subsampling for better appearance')
plt.show()
4)將多個圖4*5(四行五列)顯示在一張圖像上
import osimport matplotlib.image as mpimg
import matplotlib.pyplot as pltfolder_path = os.getcwd().replace('\\', '/')
imgpath = folder_path + "/images/001.jpg"
# matplot讀出來是RGB
image = mpimg.imread(imgpath)for i in range(20):plt.subplot(4, 5, i + 1)plt.imshow(image) # 通過for循環逐個顯示圖像plt.xticks([]) # 去掉x軸的刻度plt.yticks([]) # 去掉y軸的刻度
plt.show()
參考:
-
https://www.matplotlib.org.cn/tutorials/introductory/sample_plots.html#ellipses
-
https://matplotlib.org/gallery/lines_bars_and_markers/errorbar_subsample.html#sphx-glr-gallery-lines-bars-and-markers-errorbar-subsample-py
-
https://www.cnblogs.com/elitphil/p/12221103.html
總結
以上是生活随笔為你收集整理的Python、Matplot的subplot实现一行3列的子图绘制,并添加背景色的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Open3D 三维点云读取可视化、下采样
- 下一篇: 考摩托车驾照多少钱啊?