Python Matplotlib:将平均数添加到括号中的图例中,并添加一些可选文本
我想显示图表上每一行的平均值,并将其添加到括号中,如下图所示:“Type1(20.5)”。现在,我通过将Python Matplotlib:将平均数添加到括号中的图例中,并添加一些可选文本,python,matplotlib,Python,Matplotlib,我想显示图表上每一行的平均值,并将其添加到括号中,如下图所示:“Type1(20.5)”。现在,我通过将df.mean()添加到ax.legend或重命名图例,仅将图例显示为标签(“Type1”)或仅显示平均数(“20.5”),如下所示,如果您有许多图例,这不是最佳选项: import matplotlib.pyplot as plt import pandas as pd # create df mydic = {'2017-9-11': {'Type1': 15, 'Type2': 47,
df.mean()
添加到ax.legend
或重命名图例,仅将图例显示为标签(“Type1”)或仅显示平均数(“20.5”),如下所示,如果您有许多图例,这不是最佳选项:
import matplotlib.pyplot as plt
import pandas as pd
# create df
mydic = {'2017-9-11': {'Type1': 15, 'Type2': 47, 'Type3': 23}, '2017-9-12': {'Type1': 26, 'Type2': 39, 'Type3': 34}}
df = pd.DataFrame.from_dict(mydic, orient='index')
# plot it
fig = plt.figure()
ax = df.plot(figsize=(20, 10), linestyle='-', marker='o', linewidth=2.0)
ax.set_xlabel("", fontsize=16)
ax.set_ylabel("Count", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=14)
# Put a legend to the right of the current axis
L = ax.legend(df.mean(), loc='center left', bbox_to_anchor=(1, 0.5), fontsize=18)
#rename lagends
L.get_texts()[0].set_text('Type1 (20.5 a week)')
plt.show()
谢谢你的建议!
您可以将图例字符串定义为:
legend = ['%s (%.1f a week)' %(col_name, df[col_name].mean())
for col_name in df.columns]
您可以在plot函数中尝试以下操作: label=('type1'+'('+str(df['type1'].mean())+'a week'))
然后对每个ax重复此操作。我可以添加
/7
以获得每日编号而不是每周编号吗?我尝试了df[col_name].mean()/7
,但它不起作用…你应该可以这样做。。。我尝试了['%s(%.1f daily)'(col\u name,df[col\u name].mean()/7)来查找df.columns中的col\u name]
,它确实对我有效。不知道我第一次尝试失败的原因。谢谢!