How to make a graph from a python dictionary
I'm wanting to make a graph in python by pulling information from a dictionary.
In my case is as follows, I have a start and end date, I made the difference between the two.
If the difference is equal to 0 and 1 will add in the 2018 key.
If the difference is equal to 2 will add in the key of 2018 and 2019 and so on.
And at the end of everything I want it to show how many values it has in each key inside the graphics.
Follow Me code below:
def show_graphic(self, *args, **kwargs):
self.sql = "SELECT * FROM inventory WHERE modality = ?"
self.sql = "SELECT * FROM inventory WHERE process_start = ?"
self.result_1 = c.execute(self.sql,(self.modality_r.get(),))
#TODO: fazer o grafico apartir de um dicionario.
self.vali = {2018:[0],
2019:[0],
2020:[0],
2021:[0],
2020:[0],
2021:[0],
2022:[0],
2023:[0],
2024:[0],
2025:[0],
2026:[0],
2027:[0],
2028:[0],
2029:[0],
2030:[0]}
for row in (self.result_1):
self.moda1 = row[1]
self.date1 = row[3]
self.date2 = row[4]
self.date1 = datetime.strptime(self.date1,'%d/%m/%Y').date()
self.date2 = datetime.strptime(self.date2,'%d/%m/%Y').date()
if self.date1.year >= 2018 :
self.minus = abs((self.date1 - self.date2).days)
self.month = self.minus // 30
self.year = self.month // 12
plt.plot(self.vali.keys(), self.vali.values())
plt.xticks(self.vali.keys())
plt.yticks(self.vali.values())
plt.ylabel('Total de pessoas')
plt.xlabel('Ano')
plt.grid(True)
plt.show()
Here's an image of my database, I'm picking up his information there:
1
Author: Felipe Maia, 2019-02-01
1 answers
With matplotlib it's easy to do.
import matplotlib.pyplot as plt
If your dictionary is a hit counter, just do
dicionario = {2018:30, 2019:28, [...] ,2024:3}
plt.bar(dicionario.keys(), dicionario.values())
plt.show()
If it is a list of events, we can use list understanding and see how many events it has in each list:
dicionario = {2018:[1, 2,[...], 90],
2019:[3, 24,[...], 39],
[...]
2024:[10, 20,[...], 54]}
plt.bar(dicionario.keys(), [len(x) for x in dicionario.values()])
plt.show()
Or add the values inside it:
plt.bar(dicionario.keys(), [sum(x) for x in dicionario.values()])
plt.show()
0
Author: AlexCiuffa, 2019-02-02 01:21:11