我正在嘗試在 Python 中使用matplotlib. 具體來說,我正在使用contourf(Xm,Ym,Zm)withcolorbar并使用figX.savefig('name'),Xm,Ym,Zm作為一些網格網格來保存繪圖。
使用實際繪圖旁邊的顏色條,使用默認引數,繪圖偏離中心savefig。
如何生成一個圖形,以便生成的影像檔案以實際繪圖的中心為中心。最佳情況;調整大小,以便顏色條等不會被切斷。
我似乎無法在 的引數中找到任何可以使用的東西savefig(),而且根本不知道該怎么做。
一些代碼:
import matplotlib.pyplot as plt
import numpy as np
# make data
Xm, Ym = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Zm = (1 - Xm/2 Xm**5 Ym**3) * np.exp(-Xm**2 - Ym**2)
levels = np.linspace(Zm.min(), Zm.max(), 7)
# plot
fig, ax = plt.subplots()
cp = ax.contourf(Xm, Ym, Zm, levels=levels)
cbar = fig.colorbar(cp)
#plt.show()
fig.savefig('plots/contour-plot.png')
紅色十字應該等于紫色十字:

uj5u.com熱心網友回復:
如評論中所述,您可以使用
Update As you now introduced the problem of different figure sizes: The same logic can be applied to the height of the colorbar by creating a subGridSpec. If we want to ensure consistency in appearance for different figure size ratios, we have to take this into account while creating the GridSpecs.
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec, GridSpecFromSubplotSpec
#generate data
import numpy as np
Xm, Ym = np.meshgrid(np.linspace(-3, 3, 256), np.linspace(-3, 3, 256))
Zm = (1 - Xm/2 Xm**5 Ym**3) * np.exp(-Xm**2 - Ym**2)
levels = np.linspace(Zm.min(), Zm.max(), 7)
width = 20
height = 8
fig = plt.figure(figsize=(width, height))
#define subplot width ratios
gs_main = GridSpec(1, 3, width_ratios=[1, 2*width, 1], wspace=1/width)
#add middle plot for contour
plt_ax = fig.add_subplot(gs_main[1])
cp = plt_ax.contourf(Xm, Ym, Zm, levels=levels)
#add colorbar to middle subGridSpec on the right
gs_cbar = GridSpecFromSubplotSpec(3, 1, subplot_spec=gs_main[2], height_ratios=[1, 8, 1])
cbar_ax = fig.add_subplot(gs_cbar[1])
cbar = fig.colorbar(cp, cax=cbar_ax)
#fig.savefig('test.png')
plt.show()
This keeps the width of the colorbar, its distance from the main plot, and its relative height constant over a range of figure sizes.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/424619.html
標籤:Python matplotlib
