Alex AM
Alex AM

Reputation: 77

Plot pie chart of two dataframes in python

I am using the pie chart to plot the chart for the dataframe (df).

My code:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.DataFrame({'Subjet': ['mathematics', 'chemistry', 'physics'],
                   'points': [60, 30,10]})
df_mathematics=pd.DataFrame({'Subjet': ['Algebra', 'Logic', 'Number theory'],
                   'points': [30,15,15]})

output:

enter image description here

However, I wanted to add the subjects of df_mathematics inside the chart to mathematics, for example, algebra, 'Logic', 'Number theory' should add to the chart with their percentage mathmatics (60%).

The expected output:

enter image description here

Upvotes: 1

Views: 769

Answers (1)

rammelmueller
rammelmueller

Reputation: 1118

I came up with a minimal working example with two stacked Pie-Charts.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


df = pd.DataFrame({'Subjet': ['mathematics', 'chemistry', 'physics'],
               'points': [60, 30,10]})
df_math=pd.DataFrame({'Subjet': ['Algebra', 'Logic', 'Number theory'],
               'points': [30,15,15]})

# Values, colors and labels for the smaller ring.
math_corr = [
    60*30/60,
    60*15/60,
    60*15/60,
    30,
    10
]
colors = ["orange", "green", "red", "none", "none"]
labels = list(df_math["Subjet"]) + ["", ""]

size = 0.35
with plt.style.context("seaborn"):
    fig, ax = plt.subplots()

    # Outer with all the subjects.
    ax.pie(
        df["points"], labels=df["Subjet"],
        radius=1, wedgeprops=dict(width=size, edgecolor='w')
    )

    # Inner with only math subjects.
    ax.pie(
        math_corr, labels=labels,
        radius=1-size, colors=colors, wedgeprops=dict(width=size, edgecolor='w')
    )

    # Export
    fig.savefig("test.png")

As you can see, I made to circles by adjusting the size of the rings (taken from the official documentation here). The problem is, that this requires setting the values "by hand". The original segments for the other subjects are simply made white so that they are not shown (also they have no labels).

I hope this helps.

Upvotes: 1

Related Questions