【问题标题】:set equal amount of y-ticks for every subplot为每个子图设置相等数量的 y 刻度
【发布时间】:2020-09-15 06:39:30
【问题描述】:

我正在尝试绘制一个漂亮的子图,但我无法解决 y-ticks 数量不等的问题。例如,在下图中,“VVIX Beta”图只有 3 个刻度,而其他有 4 到 5 个刻度。理想情况下,我希望每个图表有五个 y 刻度。类似的问题已经被提出并提出了建议:

ax1.locator_params(axis='y', nbins=5)

其中 ax1 到 ax7 是七个子图。然而这没有用,输出似乎忽略了命令。有谁知道另一种方法?任何帮助都非常感谢,并提前感谢

【问题讨论】:

  • 你为什么不用plt.ylim()?为每个地块设置 y 限制
  • 我认为这不会帮助我限制 y-ticks 的数量,只会为 tick 本身设置一个限制。此外,考虑到 matplotlib 很好地选择了限制,我没有看到限制轴的理由

标签: python matplotlib plot


【解决方案1】:

一种可能的选择是使用MaxNLocator,通过:

  • nbins 作为刻度数,
  • min_n_ticksnbins 小一。

看下面的例子:

import matplotlib.ticker as ticker

def draw(ax, nBins):
    ax.plot(x,  y, 'g', label='line one', linewidth=3)
    ax.plot(x2, y2,'c', label='line two', linewidth=3)
    ax.set_title('Epic Info')
    ax.set_ylabel('Y axis')
    ax.set_xlabel('X axis')
    if nBins > 0:
        ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins=nBins, min_n_ticks=nBins-1))
    else:
        ax.yaxis.set_major_locator(ticker.MaxNLocator(nbins='auto'))
    ax.legend()
    ax.grid(True, color='k')

x =  [ 5, 8,10]; y =  [12.1,15.2, 6.3]
x2 = [ 6, 9,11]; y2 = [ 5.4,15.5, 7.6]
fig, axs = plt.subplots(2, 2, figsize=(10,7), constrained_layout=True)
fig.suptitle('Global title')
draw(axs.flat[0], 4)
draw(axs.flat[1], 5)
draw(axs.flat[2], 6)
draw(axs.flat[3], 0)
plt.show()

如您所见,它生成了 4 个几乎相同的图:

  • 3 个明确定义的 y 个刻度,
  • 最后一个带有 auto 设置。

结果是:

注意:对于某些 nBins,实际的刻度数与 意料之中,但至少您可以尝试使用我的代码来绘制您的数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-07
    • 1970-01-01
    • 1970-01-01
    • 2014-01-18
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多