Home > database >  Pie chart how to sum values when labels are the same
Pie chart how to sum values when labels are the same

Time:08-30

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?

CodePudding user response:

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()
  • Related