Using same keys for y axis and legend for bar graph

Question:

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.

Asked By: CH4

||

Answers:

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)
Answered By: falafelocelot
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.