0
votes

I am working on financial data, I intend to figure out how to create a nested pie chart on my data. Specifically, I filtered export and import product data and render nested plot for it. I did render pie chart for each, I am not able to get a correct nested pie chart or donut chart for the data. I looked into possible post on SO but didn't find any clue how to get my plot.

my current output:

import pandas as pd
from matplotlib import pyplot as plt

df5=df_from_gist_exp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
df6=df_from_gist_imp.groupby(['cty_ptn'])['qty1'].sum().nlargest(10)
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.pie(df5, labels=df5.index, autopct='%1.0f%%', radius=1)
ax2.pie(df6, labels=df6.index, autopct='%1.0f%%', radius=1)
plt.axis('equal')
plt.tight_layout()
plt.show()

current plot:

I got this plot after running the above solution:

enter image description here

desired plot

actually I want to render this pie chart or donut chart using the same data:

expected pie chart

How can I get this plot? Any trick to make this happen? Thanks

1
nested pie chart matplotlib.org/3.1.0/gallery/pie_and_polar_charts/… looks like what you want - shanecandoit
I can't recreate your variable df_from_gist without considerable effort. Could you put this in a google colab or python notebook hosted on github? I am not familiar enough with matplotlib to solve this from memory. Good luck! - shanecandoit
Getting the text in the center is easy. plt.text(0, 0, '960 K', fontsize=..., ha='center', va='bottom'). Experiment to find the best position for the metric tons. Positioning all the other texts is quite some work if you want a fully automated solution. Otherwise, just search for the best positions. - JohanC
@Jerry Please provide shanecandoit all the required information. Read about creating a minimal reproducible example - JohanC
The data from the gist seems to be 1000 lines all from argentina. df_export and df_import are empty. Please just do print(df5.to_dict()) and paste the result into your question. Same for df6. Then remove all the other pandas and csv code, as they are not important for the pie diagram. Also add the output of print(df_export['qty1'].sum()), same for import. - JohanC

1 Answers

3
votes

I just made a minimal code to achieve what you wanted:

import matplotlib.pyplot as plt
import numpy as np

# Pie chart, where the slices will be ordered and plotted counter-clockwise:
lbls = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]

# Intended to serve something like a global variable
class MyClass:
    i = -1

def func(pct, labels, vals):
    MyClass.i +=1
    # Returns absolute value against the default percentage
    # absolute = int(pct/100.*np.sum(vals))
    # Combine labels and values
    return "{:s}\n{:.0f} %".format(labels[MyClass.i], pct)


fig1, ax1 = plt.subplots()
# Pie wedgeprops with width being the donut thickness
ax1.pie(sizes, wedgeprops=dict(width=0.7), autopct=lambda pct: func(pct, lbls, sizes),
        shadow=True, startangle=90)
sumstr = 'Total = '+str(np.sum(sizes))
# String on the donut center
ax1.text(0., 0., sumstr, horizontalalignment='center', verticalalignment='center')
ax1.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.

plt.show()

This produces the following chart:

enter image description here