【问题标题】:How to add gridlines for GridSpec in Matplotlib?如何在 Matplotlib 中为 GridSpec 添加网格线?
【发布时间】:2023-04-02 02:30:01
【问题描述】:

我有一个matplotlib gridspec 的情节如下:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig2 = plt.figure(figsize=[8,8])
spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)
f2_ax1 = fig2.add_subplot(spec2[0, 0])
f2_ax2 = fig2.add_subplot(spec2[0, 1])
f2_ax3 = fig2.add_subplot(spec2[1, 0])
f2_ax4 = fig2.add_subplot(spec2[1, 1])

我想为上面的图添加网格线。我无法使用 hlines 做到这一点,因为 gridpec 属性没有对象 hlines

是否可以在 ma​​tplotlib 中为 gridspec 对象添加 gridlines,如下所示:

【问题讨论】:

标签: python matplotlib data-visualization


【解决方案1】:

这有点复杂,但以下解决方案考虑了轴上的装饰(注意网格如何位于 xlabel 下方)。如果您确切知道轴的位置,您可能会简化:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, axs = plt.subplots(2, 2, constrained_layout=True)

axs[0, 0].set_xlabel('Boo')
fig.draw_without_rendering()

trans = fig.transFigure

# line after the first column:
right = 0
for a in axs[:, 0]:
    bb = trans.inverted().transform_bbox(a.get_tightbbox(renderer=fig.canvas.get_renderer()))
    right = max(right, bb.x1)
right = right + 0.01
fig.add_artist(mpl.lines.Line2D([right, right], [0, 1], linestyle='--'))

# line after first row
bottom = 1
for a in axs[0, :]:
    bb = trans.inverted().transform_bbox(a.get_tightbbox(renderer=fig.canvas.get_renderer()))
    bottom = min(bottom, bb.y0)
bottom = bottom - 0.01
fig.add_artist(mpl.lines.Line2D([0, 1], [bottom, bottom], linestyle='--'), )
plt.show()

【讨论】:

  • 我使用的是spec = gridspec.GridSpec(ncols=2, nrows=2, figure=fig) 而不是fig, axs = plt.subplots(2, 2, constrained_layout=True)。如何在 gridspec 中获取axs
  • 使用f2_ax1等代替axs[..,..]
  • 但是使用 gridspec 和一堆 add_subplot 调用不是很地道...
  • 实际上,在我的情况下,我使用gridspec将for循环中的情节/图形添加到单个情节中@
  • 点赞here
猜你喜欢
  • 2019-11-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-22
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 1970-01-01
  • 2021-07-12
相关资源
最近更新 更多