首页 > 解决方案 > 删除重复的图例条形图 matplotlib

问题描述

我想编辑我的图例,使其仅在我使用 for 循环创建条形图时显示标签。如何删除重复的图例?它应该只显示周和月一次

这段代码给了我下面的图表

fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)

for i in range(6):
    plt.bar(x = i, data = classw.iloc[:,i], 
            height = len(classw.iloc[:,i]) - classw.iloc[:,i].isna().sum(), 
            color = (0.91, 0.1, 0.4, 1), label = 'week',
            align = 'edge', width = -0.4)
    plt.bar(x = i, data = classm.iloc[:,i], 
            height = len(classm.iloc[:,i]) - classm.iloc[:,i].isna().sum(), 
            color = 'blue', label = 'month',
            align = 'edge', width = 0.4)

plt.legend()

在此处输入图像描述

标签: python-3.xmatplotlib

解决方案


方法 1只有满足条件,才能在循环内设置图例:

fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)

for i in range(6):
    plt.bar(x = i, data = classw.iloc[:,i], 
            height = len(classw.iloc[:,i]) - classw.iloc[:,i].isna().sum(), 
            color = (0.91, 0.1, 0.4, 1), label = 'week',
            align = 'edge', width = -0.4)
    plt.bar(x = i, data = classm.iloc[:,i], 
            height = len(classm.iloc[:,i]) - classm.iloc[:,i].isna().sum(), 
            color = 'blue', label = 'month',
            align = 'edge', width = 0.4)
     if i==0:
        ax.legend()

方法2 你可以创建一个list带有标签的名字。您将None只设置一个值,然后在绘图代码中,您以这种方式索引标签列表。

fig, ax = plt.subplots(figsize = (10,6))
ax.set(xlim=(0,6))
ax.set(ylim=(0,150))
ax.set_xticklabels(edgeslist)

label_week = [None]*6
label_week[5] = 'week'

label_month = [None]*6
label_month[5] = 'month'

for i in range(6):
    plt.bar(x = i, data = [1, 2, 5, 6, 0, 1], 
            height = 5, 
            color = (0.91, 0.1, 0.4, 1), label = label_week[i],
            align = 'edge', width = -0.4)
    plt.bar(x = i, data = [1, 2, 5, 6, 0, 1], 
            height = 6, 
            color = 'blue', label = label_month[i],
            align = 'edge', width = 0.4)

plt.legend()

希望能帮助到你。


推荐阅读