【问题标题】:Python Matplotlib - turn off autoscalePython Matplotlib - 关闭自动缩放
【发布时间】:2016-12-28 01:31:28
【问题描述】:

我正在使用 matplotlib,我想通过保持两个数据集的 x 和 y 轴相同来比较 2 个数据集的图表。但是,由于数据集 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() 并没有产生我想要的结果。
  • 好的。问题重新打开。
  • 其实我现在修好了。我需要把 ax = plt.subplot() 和 ax.set_xlim() 和 ax.set_ylim() inside 循环。
  • 好吧,现在我不能重新关闭它了!我建议回答你自己的问题。您还可以使用 fig, ax_array = plt.subplots(4, 4, sharex='all', sharey='all') 并在 ax_array 中循环遍历轴对象(这是一个 4x4 numpy 数组)做得更好。

标签: python matplotlib


【解决方案1】:

您可以使用 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])
  • 但结果是一样的
  • 其实我现在修好了。我需要将 ax = plt.subplot() 和 ax.set_xlim() 和 ax.set_ylim() 放入循环中。
  • 啊哈,我明白了。我刚刚试图了解这是否在 for 循环中。另外,很抱歉我没有提到子图的 set_xlim() 和 set_ylim()。
猜你喜欢
  • 2016-10-14
  • 1970-01-01
  • 1970-01-01
  • 2020-04-06
  • 1970-01-01
  • 2021-05-28
  • 2012-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多