使用多个连接的箱线图更改 Matplotlib 中的轴刻度

Changing axis ticks in Matplotlib with multiple connected Boxplots

我正在绘制收敛图并显示与我使用的连接箱线图的平均值的偏差:

出于某种原因,Matplotlib 强制为每个箱线图打勾,我似乎无法将其删除。我当前情节的代码如下所示:

    label = ["" for i in range(160)]
    no_labels = int(np.floor(len(label)/20))
    for i in range(no_labels):
        label[i*20] = str(i*no_samples/no_labels)
    # Weird behaviour for the last label so adding it manually
    label[-1] = no_samples

    fig = plt.figure(figsize=(10,5))

    ax = fig.add_axes([0,0,1,1])
    ax.set_xlabel("Samples", labelpad=10)
    ax.set_ylabel("Error (MSE)", labelpad=10)
    ax.set_ylim(0, 0.11)

    ax.boxplot(data, flierprops=flyprops, showcaps=False, 
                boxprops=colorprops, whiskerprops={'color' : 'tab:blue'}, 
                labels=label, patch_artist=True)

我尝试了多种方法来操纵 MPL 中可用的轴刻度。

1) 尝试让 MPL 完成工作: ax.xaxis.set_major_locator(MultipleLocator(20))

2) 尝试手动设置刻度:ax.set_xticks([list_of_ticks])

3) 尝试了解决方法

    ax.xaxis.set_minor_locator(MultipleLocator(20))    

    # Removing major ticks, setting minor ticks
    ax.xaxis.set_tick_params(which='major', size=0, width=2, direction='in')
    ax.yaxis.set_tick_params(which='major', size=5, width=2, direction='in')

None 这些似乎有效,我不确定为什么。我认为这可能与我的 label 变量有关,但如果我不以这种方式包含它,MPL 为每个条目包含一个轴标签,这是一团糟。

如何在连接的箱线图中每 1000 个条目设置一次轴刻度?`

编辑:输入数据是一个形状为 (15, 160) s.t 的 numpy 数组。有 160 个箱线图,每个箱线图有 15 个样本。每个 3 个样本的 5 个箱线图的示例数据如下所示:

       np.random.rand(3,5)

>>>    array([[0.05942481, 0.03408175, 0.84021109, 0.27531937, 0.62428798],
       [0.24658313, 0.77910387, 0.2161348 , 0.39101172, 0.14038211],
       [0.40694432, 0.22979738, 0.87056873, 0.788295  , 0.29337562]])

主要问题似乎是在绘制主图之后需要更新刻度,以前从来没有。

(使用 ax = fig.add_axes([0, 0, 1, 1]) 也很不常见。标准方法是 fig, ax = plt.subplots(figsize=(10, 5)),这让 matplotlib 对绘图周围的空白有一点灵活性。)

问题的代码缺少一些变量和数据,但下面的玩具示例应该创建类似的东西:

import numpy as np
import matplotlib.pyplot as plt

no_samples = 8000
x = np.linspace(0, no_samples, 160)
no_labels = int(np.floor(len(x) / 20))
label = [f'{i * no_samples / no_labels:.0f}' for i in range(no_labels+1)]

fig = plt.figure(figsize=(10, 5))
ax = fig.add_axes([0.1, 0.1, 0.85, 0.85])

N = 100
data = np.random.normal(np.tile(100 / (x+1000), N), 0.001).reshape(N, -1)

flyprops = {'markersize':0.01}
colorprops = None
ax.boxplot(data, flierprops=flyprops, showcaps=False,
           boxprops=colorprops, whiskerprops={'color': 'tab:blue'},
           patch_artist=True)

ax.set_xlabel("Samples", labelpad=10)
ax.set_ylabel("Error (MSE)", labelpad=10)
ax.set_ylim(0, 0.11)
ax.set_xticks(range(0, len(x)+1, 20))
ax.set_xticklabels(label)

plt.show()

这里是一个设置刻度线的例子:

import matplotlib.pyplot as plt
import numpy as np

data=np.random.rand(3,50)

fig = plt.figure(figsize=(10,5))

ax = fig.add_axes([0,0,1,1])
ax.set_xlabel("Samples", labelpad=10)
ax.set_ylabel("Error (MSE)", labelpad=10)

ax.boxplot(data, 
           showcaps=False, 
           whiskerprops={'color' : 'tab:blue'}, 
           patch_artist=True
          )

plt.xticks([10, 20, 30, 40, 50],
           ["10", "20", "30", "40", "50"])

编辑: 您还可以避免弄乱字符串并像这样设置标记:

N=50
plt.xticks(np.linspace(0, N, num=6), np.linspace(0, N, num=6))

参见here and this example

可以使用

以与here类似的方式实现简单的刻度(注意data作为转置numpy数组)
import numpy as np
import matplotlib.pyplot as plt

data = np.array([ np.random.rand(100) for i in range(3) ]).T
plt.boxplot(data)
plt.xticks([1, 2, 3], ['mon', 'tue', 'wed'])