Sj293
Sj293

Reputation: 51

Plotting the mean over a bar chart

I am trying to plot a mean line over this bar chart.

enter image description here

my current code is as follows

chart_1 = agg_df[['Home Points %','Away Points %']].plot(kind='bar', title =" Home Points V Away Points", 
                                                figsize=(10, 6), legend=True, fontsize=12)
chart_1.set_xlabel("Season", fontsize=14)
chart_1.set_ylabel("Percentage of Points", fontsize=14)



plt.show()

Does anyone have any tips on how I will go about adding a horizontal line for both the home mean and the away mean?

Upvotes: 0

Views: 833

Answers (2)

Scott Boston
Scott Boston

Reputation: 153520

IIUC, you can do it like this:

import pandas as pd
import numpy as np
from seaborn import load_dataset
import matplotlib.pyplot as plt

df_tips = load_dataset('tips')
df_means = df_tips.groupby(['day', 'sex'])['tip'].mean().to_frame()

ax = df_means.unstack()['tip'].plot.bar(legend=False)
ax.hlines(df_means['tip'].mean(level=0),[-.25, .75, 1.75, 2.75], np.arange(.25,4))
plt.show()

Output:

enter image description here

Upvotes: 1

srishtigarg
srishtigarg

Reputation: 1204

This should help:

import numpy as np
chart1.axhline(np.mean(agg_df["Away Points"]), color="orange")
chart1.axhline(np.mean(agg_df["Home Points"]), color="blue")

Note: Untested code, since I could not replicate your exact dataframe.

Upvotes: 0

Related Questions