CH4
CH4

Reputation: 71

Using a dictionary to plot a bar plot and using another dictionary to give each bar a specified color

I want to use a dictionary to create a plot.

import matplotlib.pyplot as plt

data = {"rdeca":"4",
   "zelena":"5",
   "rumena":"7",
   "modra":"2",
   "roza": "9"}

colors = {"rdeca":"red",
     "zelena":"green",
     "modra":"blue",
     "roza":"pink",
     "rumena":"yellow"}

plt.bar(range(len(data)), list(data.values()), align='center')  #This is what I use to plot a bar plot with the `data` dictionary
plt.xticks(range(len(data)), list(data.keys()))
plt.show()

Output: Plot generated by the given code

What I want to achieve is to use the colors dict to assign a color to each bar in the bar plot. As you can see the data key "rdeca" should use the color "red" etc. I am trying to achieve this with color = colors.get() in the plt.bar arguments. I wasn't successful yet. I got it to use the colors but just in the order as they are in the colors dictionary. Not corresponding to the data dictionary

Upvotes: 3

Views: 2100

Answers (2)

AnhPC03
AnhPC03

Reputation: 646

Use color keyword for set bar color and use height keyword for correct value of the bars. Like this:

import matplotlib.pyplot as plt

data = {"rdeca":"4",
   "zelena":"5",
   "rumena":"7",
   "modra":"2",
   "roza": "9"}

colors = {"rdeca":"red",
     "zelena":"green",
     "modra":"blue",
     "roza":"pink",
     "rumena":"yellow"}

custom_name = [i[0] for i in data.items()]
custom_value = [int(i[1]) for i in data.items()]
custom_color = [colors[i] for i in custom_name]

plt.bar(custom_name, height=custom_value, align='center', color=custom_color)  #This is what I use to plot a bar plot with the `data` dictionary
plt.xticks(range(len(data)), list(data.keys()))
plt.show()

enter image description here

Upvotes: 0

Mandera
Mandera

Reputation: 2992

You can input the colors with the color attribute.

The list casting isn't needed, resulting in a bit cleaner code:

plt.bar(range(len(data)), data.values(), color=[colors[key] for key in data])
plt.xticks(range(len(data)), data.keys())
plt.show()

enter image description here

Upvotes: 3

Related Questions