Python Matplotlib - 关闭自动缩放

3

我正在使用matplotlib,想要比较两个数据集的图形,并保持x和y轴对于两个数据集相同。然而,由于数据集2有更小的范围,因此自动缩放总是干扰并重新调整我的图形大小。如下图所示。

def make_figure(data, param ='Customers'):  # default param is Customers
    fig = plt.figure(figsize = (18,10))

    xticks = np.arange(0, 10000, 1000)
    yticks = np.arange(0, 55000, 5000)

    i = 0
    colors = ['red','yellow','brown','orange','green','green','green','green','blue','cyan','navy','magenta']

    ax1 = fig.add_subplot(3,4,1)
    ax1.set_xticks(xticks)
    ax1.set_yticks(yticks)
    ax1.autoscale(False, tight=False)

    for assortment in ['a','b','c']:
        for storetype in ['a','b','c','d']:

            datax = data[param][data.StoreType == storetype][data.Assortment == assortment]
            datay = data['Sales'][data.StoreType == storetype][data.Assortment == assortment]
            plt.subplot(3, 4, i+1, sharex=ax1, sharey=ax1)
            plt.title('Assortment ' + assortment + ' StoreType ' + storetype)
            plt.scatter(y = datay, x = datax, c=colors[i], alpha=.65)

            if i % 4 == 0:
                plt.ylabel('Sales')

            if i >= 8:
                plt.xlabel(str(param))

            i += 1

    plt.tight_layout()

    return plt.show()

数据集1

这里输入图片描述

数据集2

这里输入图片描述


@tacaswell:我知道这两个问题听起来很相似,但我尝试了set_xlim(),它没有产生我想要的结果。 - M_D
问题已重新开放。 - tacaswell
实际上,现在我已经修复了它。我需要将ax = plt.subplot()和ax.set_xlim()以及ax.set_ylim() 放在循环内部。 - M_D
好的,现在我无法重新关闭它!我建议回答你自己的问题。你也可以使用fig, ax_array = plt.subplots(4, 4, sharex='all', sharey='all')并循环遍历ax_array中的轴对象(它是一个4x4的numpy数组),这样做可能会更好。 - tacaswell
1个回答

0

您可以使用xlim和ylim函数来设置每个轴的限制。如果限制是恒定的,例如:

# Set the limits and disable scaling
plt.xlim(0, 8000)
plt.ylim(0, 40000)
plt.autoscale(False)

一个更通用的解决方案是事先基于您计划绘制的所有数据集确定您的最大限制,并相应地设置限制。

我实际尝试过。我添加了ax1.set_xlim([0,8000])和ax1.set_ylim([0,45000])。 - M_D
但结果是相同的 - M_D
实际上,我已经修复了它。我需要将ax = plt.subplot()和ax.set_xlim()以及ax.set_ylim()放在循环内部。 - M_D
啊哈,我明白了。我刚才试图理解这是否在for循环内部。另外,抱歉我没有提到子图的set_xlim()和set_ylim()。 - Wes Doyle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接