Pie chart how to sum values when labels are the same

Question:

I made this.

query = "SELECT towar, sztuki, zysk FROM sklep"
mycr.execute(query)
wyniki = mycr.fetchall()
nazwy = []
sztuki = []
for a in wyniki:
 nazwy.append(a[0])
 sztuki.append(a[1])
plt.pie(sztuki, labels=nazwy, autopct='%.1f%%')
plt.show()


Everythink works fine but how to sum percentages when labels are the same?
For example how to sum percentages of "woda" labels?

Asked By: MichaƂ

||

Answers:

I’d prefer to use dictionaries. In your case, nazwy is the key (labels) and sztuki are the values stored in dictionary. Here is your modified code:

query = "SELECT towar, sztuki, zysk FROM sklep"
mycr.execute(query)
wyniki = mycr.fetchall()
data_dict = {}
for a in wyniki:
    if a[0] in data_dict.keys():
        data_dict[a[0]] = data_dict[a[0]]+a[1]
    else:
        data_dict[a[0]] = a[1]

nazwy = list(data_dict.keys())
sztuki = list(data_dict.values())
# plotting
plt.pie(sztuki, labels=nazwy, autopct='%.1f%%')
plt.show()
Answered By: saad_saeed
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.