How can I create a aggregate plot in Python across a column?

Viewed 24

I want to make a graph with this Dataframe in Python:

the DataFrame

The Age column represent the age of people and the Travel Insurance column shows 1 for customer and 0 for non-customer.

Does anyone know how to make a graph to show the percentage of customers in each age category?

Thank you so much!

The expected outcome is this:

enter image description here

1 Answers

If you want to just find percentage based on age for varying ages, you can find the distribution of ages using Counter. Since you have not provided your DataFrame, I have assumed its column as a list on my own and carried out the procedure for you.

import pandas as pd
from collections import Counter
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
import seaborn as sns
ages = [28,28,28,28,29,29,29,29,29,30,30,30,31,31
       ,31,31,31,31,31,31,32,32,32,32,32,32,33,33,33,33,33,33,34,34,34,34]
df = pd.DataFrame()
df['age'] = ages
distribution = dict(Counter(df['age']))
x_ax = distribution.keys()
y_ax = list(distribution.values())
total = sum(y_ax)
for i in range(len(y_ax)):
    y_ax[i] = y_ax[i] * 100 / total  
fig, ax = plt.subplots()
plt.bar(x_ax, y_ax)
plt.xlabel('Age')
plt.ylabel('Percentage')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())

This returns a blue monochrome plot, however matching the rest of your specifications.

enter image description here

Related