Search code examples
pythonpython-3.xmatplotliblabelaxis-labels

Add label to bar chart in python


Like this

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()

Hi Everyone, I was labeling my bar chart and it has three color 'green', 'red' and 'blue' I just want to show on upper right corner of my graph with name plus it color.graph of code with three color


Solution

  • Use mpatches to build your legend manually:

    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)
    

    Full code:

    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()
    

    enter image description here