how to plot sns.boxplot with mean instead of median in python

To plot a Seaborn boxplot with mean instead of median in Python, you can modify the underlying matplotlib function. Here's an example using the tips dataset:

main.py
import seaborn as sns
import matplotlib.pyplot as plt

# Load example dataset
tips = sns.load_dataset("tips")

# Define the boxplot function with mean instead of median
def boxplot_mean(data, y, x, **kwargs):
    ax = sns.boxplot(data=data, y=y, x=x, **kwargs)
    # Calculate mean values
    means = data.groupby(x)[y].mean()
    for xtick in ax.get_xticks():
        ax.text(xtick, means[xtick], f"{means[xtick]:.2f}", 
                horizontalalignment='center', color='w', weight='bold')

# Plot the boxplot with mean
boxplot_mean(data=tips, y='total_bill', x='day')

# Show the plot
plt.show()
601 chars
21 lines

In this code, we define a custom function boxplot_mean that extends the functionality of sns.boxplot. Inside this function, we calculate the mean values using groupby and mean functions. Then, we iterate over the x-ticks of the plot and use ax.text to annotate the mean values on the plot.

This will create a boxplot with mean values instead of median. You can customize further by modifying the aesthetics and labels of the plot.

gistlibby LogSnag