在matplotlib pyp中使轴的长度相同

2024-09-24 22:26:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使正方形独立于轴的单位。例如,我知道我可以将图形尺寸设置为figure(figsize=(10, 10)),也可以将轴比例比设置为set_aspect('equal'),但如何使实际轴长度相等,例如,使xaxis和yaxis各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()

Tags: importgslenmatplotlibfigpltfigureset
1条回答
网友
1楼 · 发布于 2024-09-24 22:26:13

使用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])

相关问题 更多 >