当前位置: 代码迷 >> python >> 如何抑制matplotlib轴中的主要标签xticks?
  详细解决方案

如何抑制matplotlib轴中的主要标签xticks?

热度:33   发布时间:2023-06-27 21:29:11.0

该代码为细分为三组数据的样本生成单独的箱线图。 因此,数据集1具有样本A,B和C,依此类推。 当我绘制x轴时,我只想要样品名称(“样品A”,“样品B”等),而不是主要标签(即“数据集1”,“数据集2”等)-我不知道如何抑制主要标签。

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

#build dataset as dictionary
data = {}
data['dataset1'] = {}
data['dataset2'] = {}
data['dataset3'] = {}

#simulate data
n = 100
for k,v in data.iteritems():
    upper = random.randint(0, 1000)
    v['sample A'] = np.random.uniform(0, upper, size=n)
    v['sample B'] = np.random.uniform(0, upper, size=n)
    v['sample C'] = np.random.uniform(0, upper, size=n)

fig, axes = plt.subplots(ncols=3, sharey=True)
fig.subplots_adjust(wspace=0)

#build subplots
for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
    ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']])
    ax.set(xticklabels=['sample A', 'sample B', 'sample C'], xlabel=name)
    ax.margins(0.05) # Optional

#plot labels
for ax in fig.axes:
    plt.sca(ax)
    plt.xticks(ha = 'right', rotation=45)

plt.show()

如果您想知道这对我的实际数据集造成了主要的显示问题。

其他两个解决方案都首先创建x标签,然后将其删除/隐藏。 最简单的方法是不首先放置标签。

只需使用

ax.set(xticklabels=['sample A', 'sample B', 'sample C'])

没有传递参数xlabel=name

一个简单的解决方案是用空字符串替换标签,或使其不可见:

for ax in fig.axes:
    plt.xlabel('')
    # or
    # ax.xaxis.label.set_visible(False)

设置标签不可见

#build subplots
for ax, name in zip(axes, ['dataset1', 'dataset2', 'dataset3']):
    ax.boxplot([data[name][item] for item in ['sample A', 'sample B', 'sample C']])
    ax.set(xticklabels=['sample A', 'sample B', 'sample C'], xlabel=name)
    ax.margins(0.05) # Optional
    ax.xaxis.label.set_visible(False)     # Add this to suppress the major labels