【问题标题】:Add label to bar chart in python [duplicate]在python中为条形图添加标签[重复]
【发布时间】:2021-10-21 17:46:02
【问题描述】:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot()

N = 5
ind = np.arange(N)
width = 0.5
vals = []

colors = []
add_c=[(1,0),(4,1),(-1,0),(3,0),(2,1)]
for v in add_c:
    vals.append(v[0])
    if v[0] == -1:
        colors.append('r')
    else:
        if v[1] == 0:
            colors.append('b')
        else:
            colors.append('g')

ax.bar(ind, vals, width, color=colors,label=[{'r':'red'}])
ax.legend()
ax.axhline(y = 0, color = 'black', linestyle = '-')
plt.show()

大家好,我正在标记我的条形图,它有“绿色”、“红色”和“蓝色”三种颜色,我只想在图表的右上角显示名称和颜色。@ 987654322@

【问题讨论】:

    标签: python python-3.x matplotlib label axis-labels


    【解决方案1】:

    使用mpatches 手动构建您的图例:

    import matplotlib.patches as mpatches:
    
    ...
    
    color_dict = {'cat1': 'r', 'cat2': 'g', 'cat3': 'b'}
    labels = color_dict.keys()
    handles = [mpatches.Rectangle((0,0),1,1, color=color_dict[l]) for l in labels]
    
    ax.bar(ind, vals, width, color=colors)
    ax.legend(handles, labels)
    

    完整代码:

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.patches as mpatches
    
    fig = plt.figure()
    ax = fig.add_subplot()
    
    N = 5
    ind = np.arange(N)
    width = 0.5
    vals = []
    
    colors = []
    add_c=[(1,0),(4,1),(-1,0),(3,0),(2,1)]
    for v in add_c:
        vals.append(v[0])
        if v[0] == -1:
            colors.append('r')
        else:
            if v[1] == 0:
                colors.append('b')
            else:
                colors.append('g')
    
    color_dict = {'cat1': 'r', 'cat2': 'g', 'cat3': 'b'}
    labels = color_dict.keys()
    handles = [mpatches.Rectangle((0,0),1,1, color=color_dict[l]) for l in labels]
    
    ax.bar(ind, vals, width, color=colors)
    ax.legend(handles, labels)
    ax.axhline(y = 0, color = 'black', linestyle = '-')
    plt.show()
    

    【讨论】:

    • 您能解释一下 Rectangle((0,0),1,1 以及 (0,0),1,1 的意义何在
    • Rectangle 画一个矩形...最好的解释是matplotlib的文档:matplotlib.org/stable/api/_as_gen/…。不客气……
    猜你喜欢
    • 2018-10-01
    • 2022-01-11
    • 2021-06-02
    • 2021-03-27
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 2022-01-16
    相关资源
    最近更新 更多