Home > database >  Using a dictionary to plot a bar plot and using another dictionary to give each bar a specified colo
Using a dictionary to plot a bar plot and using another dictionary to give each bar a specified colo

Time:07-23

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

CodePudding user response:

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

CodePudding user response:

try this, Base your data iterate over dict colors and find color and use in plotting. (use dict.get(key, default_value) for those bars if not exist in dcit colors. (I set 'black'))

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', 
                  color=[colors.get(k, 'black') for k,v in data.items()])
plt.xticks(range(len(data)), list(data.keys()))
plt.show()

enter image description here

CodePudding user response:

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

  • Related