0

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

1 Answers1

1

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

Corralien
  • 109,409
  • 8
  • 28
  • 52
  • Can you please explain Rectangle((0,0),1,1 and what is significant of (0,0),1,1 – OneTouchForHeight Aug 20 '21 at 14:28
  • Rectangle draws a rectangle... The best explanation is the documentation of matplotlib: https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Rectangle.html. And you're welcome... – Corralien Aug 20 '21 at 19:28