python - 在 matplotlib pyplot 中使轴长度相同

标签 python matplotlib

我想让正方形独立于轴单位。我知道我可以将图形尺寸设置为等于 figure(figsize=(10, 10)) 例如,我可以将轴比例设置为等于 set_aspect('equal'),但是如何强制实际轴长度相等,例如,使 x 轴和 y 轴各长 10 英寸?

编辑示例代码

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib.ticker import MaxNLocator
import numpy as np

x1 = 1
y1 = [10., 1000.]
err1 = 0.00865
x2 = 2
y2 = [9., 900.]
err2 = 0.00658

len_xaxis,len_yaxis = 5.,5. #fix here your numbers
xspace, yspace = .9, .9 # change the size of the void border here.
x_fig,y_fig = len_xaxis / xspace, len_yaxis / yspace

for i in range(2):
    plt.clf()
    #    fig = plt.figure(figsize=(6, 6))
    fig = plt.figure(figsize=(x_fig,y_fig))
    plt.subplots_adjust(left=1-xspace, right = xspace, top=yspace, bottom = 1-yspace)
    gs = gridspec.GridSpec(3, 1)
    gs.update(hspace=0., wspace=0.)
    ax1 = plt.subplot(gs[0:2, 0])

    ax1.errorbar(x1, y1[i], yerr=err1)
    ax1.errorbar(x2, y2[i], yerr=err2)

    ax1.invert_yaxis()

    plt.setp(ax1.get_xticklabels(), visible=False)  # Remove x-labels between the plots
    plt.xlim(0, 3)

    ax2 = plt.subplot(gs[2, 0], sharex=ax1)

    nbins = len(ax1.get_yticklabels())
    ax1.yaxis.set_major_locator(MaxNLocator(nbins=8, prune='both'))
    nbins = len(ax2.get_yticklabels())
    ax2.yaxis.set_major_locator(MaxNLocator(nbins=6, prune='both'))

    plt.tight_layout()
    plt.savefig('prune_%d.png' % i)
    plt.close()

最佳答案

使用plt.subplots_adjust()函数。 5 英寸而不是 10 英寸的示例:

len_xaxis,len_yaxis = 5.,5. #fix here your numbers

xspace, yspace = .9, .9 # change the size of the void border here.

x_fig,y_fig = len_xaxis / xspace, len_yaxis / yspace
figure(figsize=(x_fig,y_fig))
plt.subplots_adjust(left=1-xspace, right = xspace, top=yspace, bottom = 1-yspace)
plot([1,2,3],[-1,3,5])

关于python - 在 matplotlib pyplot 中使轴长度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27932162/

相关文章:

python - 绘制水位线降水图

python - 使用 Pandas 生成 3D "matrix",基于比较两个数据帧 [Python]

python - 二维数组的numpy 3d张量

python - Mat plot lib 绘制图像而不是保存(facebook detectron 代码)

python - 拟合 Von Mises 分布的圆形直方图

python matplotlib imshow 在数据数组中具有不同的长度

python - 如何在 Python 中查找字典数组(或字典的字典)的形状或维度

python - 使用 python requests 伪装成浏览器并下载文件

python numpy 排序特征值

python - 在 matplotlib 中,如何绘制多个数据集的条形图以将最小的条放在前面?