【问题标题】:matplotlib subplot boxplot hiding some axis labelsmatplotlib subplot boxplot 隐藏一些轴标签
【发布时间】:2017-04-23 15:32:07
【问题描述】:

我想遍历列表并绘制每个列表的箱线图。因为数据不能全部放入内存,所以我无法分配预定义数量的箱线图来绘制,所以我使用 subplot 函数迭代地添加图。

我的问题是轴标签没有被添加到带有箱线图的图中,并且只显示了最后一个标签。如何使用 subplot 迭代地标记箱线图。

下面是我想要做的一个简化示例。尽管实际上我实际上是在循环中回收同一个列表,而不是遍历列表列表,但它可以说明问题。可以看出,yaxis 中只设置了“lb”,并且第一个底部箱线图没有显示“la”,

谢谢。

%matplotlib inline
import matplotlib.pyplot as plt

la = [24, 28, 31, 34, 38, 40, 41, 42, 43, 44]
lb = [5, 8, 10, 12, 15, 18, 21, 25, 30, 39]
names = ['la', 'lb']
myList = [la] + [lb]
myList

# set fig for boxplots
fig, ax = plt.subplots(sharex=True)
# Add a horizontal grid to the plot
ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
ax.set_axisbelow(True)
ax.set_title('Some Title')

for i,l in enumerate(myList):
    ax.boxplot(l, vert=False, positions = [i])
    ax.set_yticklabels([names[i]])

ax.set_ylim(-0.5, len(myList)-0.5)

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    在循环内设置标签会覆盖之前的刻度标签。所以标签应该设置在循环之外。您还需要确保两个标签实际上都有刻度。

    因此添加一个解决方案

    ax.set_yticks(range(len(myList)))
    ax.set_yticklabels(names)
    

    在循环之外。

    完整代码:

    import matplotlib.pyplot as plt
    
    la = [24, 28, 31, 34, 38, 40, 41, 42, 43, 44]
    lb = [5, 8, 10, 12, 15, 18, 21, 25, 30, 39]
    names = ['la', 'lb']
    myList = [la] + [lb]
    myList
    
    # set fig for boxplots
    fig, ax = plt.subplots(sharex=True)
    # Add a horizontal grid to the plot
    ax.xaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
    ax.set_axisbelow(True)
    ax.set_title('Some Title')
    
    for i,l in enumerate(myList):
        ax.boxplot(l, vert=False, positions = [i])
    
    ax.set_yticks(range(len(myList)))
    ax.set_yticklabels(names)
    
    ax.set_ylim(-0.5, len(myList)-0.5)
    
    plt.show()
    

    【讨论】:

    • 太棒了。我之前尝试过类似的方法,但也没有设置刻度,结果与我的问题相同。所以我会引用你的句子“你还需要确保两个标签实际上都有刻度。”根据需要做这个把戏。
    • 确实如此。完成。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 2021-01-11
    • 2020-09-14
    • 2021-11-05
    • 2020-09-23
    • 2022-07-04
    相关资源
    最近更新 更多