Using same keys for y axis and legend for bar graph

I have some data that I want to plot.

import matplotlib.pyplot as plt

data = {
    "key 1" : 3,
    "key 2" : 5, 
    "key 3" : 7
}

colors = {
    "key 1" : "red",
    "key 2" : "green",
    "key 3" :"blue"
}

x = data.keys() 
y = data.values()

plt.bar(x, y, color=[colors[k] for k in data])
plt.legend(y)

This is my output:
enter image description here

I want the legend showing: red color – key 1, green color – key2 etc. and remove the keys from the y axis.

>Solution :

You can do that pretty easily using this post:

handles = plt.bar(x, y, color=[colors[k] for k in data])
plt.legend(handles, x)

Leave a Reply