繁体   English   中英

x-labels 在 matplotlib 图上呈现两次

[英]x-labels rendered twice on matplotlib plot

我有一个在 x 轴上使用 9 个标签的图。 但是,由于我已将绘图分成两个轴,因此由于某种原因,它似乎需要 18 个标签(因此添加了空字符串列表)。

这似乎使 x-labels 被渲染两次,使它们看起来有一个粗体字。 附上问题的图片。

这是我正在使用的当前代码。 我为代码的质量道歉。 我是 matplotlib 的新手。

    benchmark_data = all_benchmark_data[loader.pingpongKey]

    fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True, figsize=(9,7), dpi=80)
    fig.subplots_adjust(hspace=0.05)

    ax1.boxplot(benchmark_data.values())
    ax2.boxplot(benchmark_data.values())

    ax1.set_ylim(380, 650) 
    ax2.set_ylim(110, 180)

    # hide the spines between ax and ax2
    ax1.spines.bottom.set_visible(False)
    ax2.spines.top.set_visible(False)
    ax1.xaxis.tick_top()
    ax1.tick_params(labeltop=False)  # don't put tick labels at the top
    ax2.xaxis.tick_bottom()

    ax1.tick_params(axis='both', labelsize=10)
    ax2.tick_params(axis='both', labelsize=10)

    xlabels = ['', '', '', '', '', '', '', '', ''] + (list(benchmark_data.keys()))
    ax1.set_xticklabels(xlabels)
    ax1.set_ylabel('Time (ms)', fontsize=10)
    ax1.yaxis.set_label_coords(-0.06,0)
    #ax2.set_ylabel('Time (ms)', fontsize=10)
    plt.xticks(fontsize=10, rotation=45)

    ax1.yaxis.set_major_locator(ticker.MaxNLocator(nbins=5, min_n_ticks=5))
    ax2.yaxis.set_major_locator(ticker.MaxNLocator(nbins=5, min_n_ticks=5))

    d = .5  # proportion of vertical to horizontal extent of the slanted line
    kwargs = dict(marker=[(-1, -d), (1, d)], markersize=12,
                linestyle="none", color='k', mec='k', mew=1, clip_on=False)
    ax1.plot([0, 1], [0, 0], transform=ax1.transAxes, **kwargs)
    ax2.plot([0, 1], [1, 1], transform=ax2.transAxes, **kwargs)

    plt.tight_layout()
    plt.savefig('plots/boxplots/' + loader.pingpongKey + '-boxplot.png', 
    bbox_inches='tight')

在此处输入图像描述

因为您使用的是sharex=True ,所以第二次绘制箱线图时,您将创建另外 9 个添加到轴的刻度(这在ax1ax2之间是共同的)。 您的解决方案是关闭sharex (无论如何,轴都会对齐)并在 ax2 上设置ax2

# No sharex.
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9,7), dpi=80)

# ...

# Set ticks for ax2 instead of ax1 and only the 9 labels are needed.
ax2.set_xticklabels(list(benchmark_data.keys()))

暂无
暂无

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

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