简体   繁体   English

matplotlib:添加刻度标签时删除子图填充

[英]matplotlib: Remove subplot padding when adding tick labels

I have an issue where adding tick labels interferes with my given padding preference between subplots. 我有一个问题,其中添加刻度线标签会干扰子图之间给定的填充首选项。 What I want, is a tight_layout with no padding at all in between, but with some custom ticks along the x-axis. 我想要的是一个tight_layout ,之间完全没有填充,但是沿x轴有一些自定义刻度。 This snippet and resulting figures shows the issue: 此代码段和生成的数字显示了该问题:

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

fig_names = ['fig1']
gs = gridspec.GridSpec(1, len(fig_names))
gs.update(hspace=0.0)
figs = dict()

for fig_name in fig_names:
    figs[fig_name] = plt.figure(figsize=(3*len(fig_names),6))
    for i in range(0,len(fig_names)):
        ax = figs[fig_name].add_subplot(gs[i])
        ax.plot([0,1],[0,1], 'r-')
        if i != 0:
            ax.set_yticks(list())
            ax.set_yticklabels(list())
        ax.set_xticks(list())
        ax.set_xticklabels(list())

for name,fig in figs.items():
    fig.text(0.5, 0.03, 'Common xlabel', ha='center', va='center')
    gs.tight_layout(fig, h_pad=0.0, w_pad=0.0)
    ax = fig.add_subplot(gs[len(fig_names)-1])
    ax.legend(('Some plot'), loc=2)

plt.show()

没有刻度标签,没有填充

By changing the corresponding lines into: 通过将相应的行更改为:

ax.set_xticks([0.5,1.0])
ax.set_xticklabels(['0.5','1.0'])

...unwanted padding is added to the graphs. ...将不必要的填充添加到图形中。 添加刻度线标签,出现填充

How can I customize the tick text so that the graph plots has no padding, regardless of what tick text I enter? 我如何自定义刻度线文本,以便无论输入什么刻度线文本,图形图都没有填充? The text may "overlap" with the next subplot. 文本可能与下一个子图“重叠”。

Perhaps you could simply create the axes with plt.subplots : 也许您可以简单地使用plt.subplots创建轴:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(ncols=2, sharey=True)
for ax in axs:
    ax.plot([0,1],[0,1], 'r-')
    ax.set_xticks([0.5,1.0])
    ax.set_xticklabels(['0.5','1.0'])
axs[-1].legend(('Some plot'), loc=2)
for ax in axs[1:]:
    ax.yaxis.set_visible(False)
fig.subplots_adjust(wspace=0)
plt.show()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM