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

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain Rectangle((0,0),1,1 and what is significant of (0,0),1,1
Rectangle draws a rectangle... The best explanation is the documentation of matplotlib: matplotlib.org/stable/api/_as_gen/…. And you're welcome...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.