【问题标题】:Remove (sub)plot, but keep axis label in matplotlib删除(子)图,但在 matplotlib 中保留轴标签
【发布时间】:2018-08-15 18:37:23
【问题描述】:

我想在 matplotlib 中创建一个子图,比如 2 行和 2 列,但我只有 3 件事要绘制,并且希望保持 左下角 子图为空。但是,我仍然希望在那个位置有一个 y 轴标签,它应该是指整个第二行。

这是我目前的代码:

import matplotlib.pyplot as plt

x = [0, 1]
y = [2, 3]

ax = plt.subplot2grid((2, 2), (0, 0))
ax.plot(x, y)
ax.set_ylabel('first row')

ax = plt.subplot2grid((2, 2), (0, 1))
ax.plot(x, y)

ax = plt.subplot2grid((2, 2), (1, 0))
ax.set_ylabel('second row')
# ax.axis('off')     <---- This would remove the label, too

ax = plt.subplot2grid((2, 2), (1, 1))
ax.plot(x, y)

plt.show()

我尝试过使用axis('off'),但这也删除了标签。 (同样,如果我将它向上移动一行,即在 ax.set_ylabel('second row') 上方。

所以到目前为止的结果是这样的:

我希望空的白色框(不仅仅是它的黑色边界框或刻度和刻度标签)消失。这可能吗?如果可以,我该如何实现?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    不幸的是,您需要单独删除轴的元素以保留 ylabel,因为 ylabel 本身也是轴的元素。

    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(2,2)
    fig.set_facecolor("#ecfaff")
    for i, ax in enumerate(axes.flatten()):
        if i!=2:
            ax.plot([3,4,6])
        if not i%2:
            ax.set_ylabel("My label")
    
    # make xaxis invisibel
    axes[1,0].xaxis.set_visible(False)
    # make spines (the box) invisible
    plt.setp(axes[1,0].spines.values(), visible=False)
    # remove ticks and labels for the left axis
    axes[1,0].tick_params(left=False, labelleft=False)
    #remove background patch (only needed for non-white background)
    axes[1,0].patch.set_visible(False)
    
    plt.show()
    

    【讨论】:

    • 谢谢,这成功了。为我的初始示例量身定制,在此解决方案使用axes[1,0] 的任何地方使用ax。此外,我还必须调整一件事,以便同时删除左下图中右侧的 y 轴刻度:ax.tick_params(left=False, labelleft=False, right=False)
    【解决方案2】:

    更清洁的方式:

    plt.gca().set_yticklabels([])
    plt.gca().set_xticklabels([])
    plt.gca().set_xticks([])
    plt.gca().set_yticks([])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多