在条形图上绘制均值

时间:2021-01-04 18:05:12

标签: python pandas matplotlib data-visualization

我正在尝试在此条形图上绘制一条平均线。

enter image description here

我目前的代码如下

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()

有人对我将如何为主场和客场均值添加一条水平线有任何建议吗?

2 个答案:

答案 0 :(得分:0)

这应该会有所帮助:

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

注意:未经测试的代码,因为我无法复制您的确切数据框。

答案 1 :(得分:0)

IIUC,你可以这样做:

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()

输出:

enter image description here

相关问题