如何将数据框属性值映射到 Matplotlib 中图例中的自定义字符串?

How to map dataframe attribute values to custom string in legend in Matplotlib?

我正在尝试创建情节

pd.crosstab(df['cardio'], df['cholesterol']).plot(kind = 'bar') 
plt.xlabel('0 = No Heart Disease, 1 = Heart Disease Present')
plt.ylabel('Number of people')
#####plt.legend(['Above Normal','High', 'Normal'])
plt.legend(df['cholesterol'])
plt.title("Distribution w.r.t cholesterol")
plt.show()

数据框的胆固醇值分别为 1、2、3,分别表示正常、高于正常、远高于正常。上面的代码给出了1,2,3的图例。有没有办法用自定义字符串替换图例值,即我可以定义1应该在图例中显示为“正常”,2为“高于正常”和 3 为“远高于正常水平”。提前致谢。

数据是使用评论中的信息独立创建的。我还汇总了 pandas 图,因为您可以为轴设置标题和标签。然后,您可以从创建的图例中获取句柄和标签,并指定要替换的标签。

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import random

df = pd.DataFrame({'cardio': random.choices([0,1], k=100),
                   'cholesterol': random.choices([1,2,3], k=100)})

ax = pd.crosstab(df['cardio'], df['cholesterol']).plot(kind = 'bar',
                                                  title='Distribution w.r.t cholesterol',
                                                  xlabel='0 = No Heart Disease, 1 = Heart Disease Present',
                                                  ylabel='Number of people'
                                                 )
new_labels = ['Above Normal','High', 'Normal']
handler, _ = ax.get_legend_handles_labels()
ax.legend(handler, new_labels, loc='upper center', title='cholesterol')