简体   繁体   English

x-labels 在 matplotlib 图上呈现两次

[英]x-labels rendered twice on matplotlib plot

I have a plot that uses 9 labels on the x-axis.我有一个在 x 轴上使用 9 个标签的图。 However, because I have split up the plot into two axes, it seems that it requires 18 labels (hence the added list of empty strings) instead for some reason.但是,由于我已将绘图分成两个轴,因此由于某种原因,它似乎需要 18 个标签(因此添加了空字符串列表)。

This seems to make the x-labels be rendered twice, making them seem to have a bold typeface.这似乎使 x-labels 被渲染两次,使它们看起来有一个粗体字。 Image of the problem is attached.附上问题的图片。

And here is the current code I'm using.这是我正在使用的当前代码。 I apologize for the quality of the code.我为代码的质量道歉。 I am new to matplotlib.我是 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')

在此处输入图像描述

Because you are using sharex=True , the second time you plot the boxplot you will create another 9 ticks that are added to the axis (which is in common between ax1 and ax2 ).因为您使用的是sharex=True ,所以第二次绘制箱线图时,您将创建另外 9 个添加到轴的刻度(这在ax1ax2之间是共同的)。 The solution in your case is to turn off sharex (the axis will be aligned anyway) and set the xticklabels on ax2 :您的解决方案是关闭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