How to make a faceted bar plot

Viewed 27

I have a question I'm trying to solve.

What is the average claim amount for gender and age categories and suitably represent the above using a facetted bar chart, one facet that represents fraudulent claims and the other for non-fraudulent claims.

How do I make a facet bar chart. Using matplotlib and seaborn.

1 Answers

If we check the documentation for seaborn, we find that they have a function for faceted categorical plots.

You'll need to organize your data into a long format, and indicate the appropriate arguments into the catplot function, with kind being set to "bar".

Example:

import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib.pyplot import show
np.random.seed(42)

df = pd.DataFrame({
    "Gender": np.random.choice(["Male", "Female"], 100),
    "AgeGroup": np.random.choice(["18-40", "40-65", "65+"], 100),
    "IsFraud": np.random.choice([True, False], 100),
    "ClaimAmount": np.random.randint(100, 1000, 100),
})

g = sns.catplot(data=df, x="Gender", y="ClaimAmount", hue="AgeGroup", col="IsFraud", kind="bar")
show()
Related