Matplotlib:限制绘图宽度,同时允许灵活的高度

mez*_*ano 5 python plot matplotlib

我想要实现的是具有等比例纵横比固定宽度动态选择高度的图。

\n\n

为了使这一点更加具体,请考虑以下绘图示例:

\n\n
import matplotlib as mpl\nimport matplotlib.pyplot as plt\n\ndef example_figure(slope):\n    #\xc2\xa0Create a new figure\n    fig = plt.figure()\n    ax = fig.add_subplot(111)\n\n    #\xc2\xa0Set axes to equal aspect ratio\n    ax.set_aspect(\'equal\')\n\n    # Plot a line with a given slope,\n    #\xc2\xa0starting from the origin\n    ax.plot([x * slope for x in range(5)])\n\n    # Output the result\n    return fig\n
Run Code Online (Sandbox Code Playgroud)\n\n

此示例代码将产生不同宽度的图形,具体取决于数据:

\n\n
example_figure(1).show()\n
Run Code Online (Sandbox Code Playgroud)\n\n

斜率为 1 的线

\n\n
example_figure(2).show()\n
Run Code Online (Sandbox Code Playgroud)\n\n

斜率为 2 的线

\n\n

Matplotlib 似乎将绘图调整到一定的高度,然后选择宽度以适应纵横比。对我来说理想的结果是相反的——上面的两个图将具有相同的宽度,但第二个图将是第一个图的两倍高。

\n\n
\n\n

奖励 — 难度级别:Gridspec

\n\n

从长远来看,我想创建一个网格,其中一个图具有固定的纵横比,并且我想再次精确对齐图表。

\n\n
#\xc2\xa0Create a 2x1 grid\nimport matplotlib.gridspec as gridspec\ngs = gridspec.GridSpec(2, 1)\n\n# Create the overall graphic, containing\n# the top and bottom figures\nfig = plt.figure()\nax1 = fig.add_subplot(gs[0, :], aspect=\'equal\')\nax2 = fig.add_subplot(gs[1, :])\n\n#\xc2\xa0Plot the lines as before\nax1.plot(range(5))\nax2.plot(range(5))\n\n# Show the figure\nfig.show()\n
Run Code Online (Sandbox Code Playgroud)\n\n

结果是这样的:

\n\n

同一张图两次,上面的宽高比固定

\n\n
\n\n

再次,我的问题是:如何创建高度根据数据灵活变化、同时宽度固定的图表?

\n\n

避免潜在误解的两点:

\n\n
    \n
  • 在上面的示例中,两个图具有相同的 x 轴。这不能被认为是理所当然的。
  • \n
  • 我知道height_ratiosgridspec 中的选项。我可以计算数据的维度,并设置比率,但不幸的是,这不能直接控制图形,而是控制它们的边界框,因此(取决于轴标签),仍然会出现不同宽度的图形。\n理想情况下,绘图画布应完全对齐。
  • \n
  • 另一个未解决的问题类似,但稍微复杂一些。
  • \n
\n\n

非常欢迎任何想法和建议,如果需要,我很乐意进一步具体说明问题。非常感谢您考虑这一点!

\n

小智 1

您是否尝试过使用 Fig.set_figwidth() 来修复宽度?