matplotlib 如何在python中用颜色渐变按字母顺序绘制标签?

gblwokeq  于 2023-01-31  发布在  Python
关注(0)|答案(1)|浏览(206)

我想在python中用颜色梯度按字母顺序绘制标签“nutrition_grade_fr”。
下面是我的图的代码,但它没有按字母顺序显示标签,也没有相应的色调:

import seaborn as sns
import matplotlib.pyplot as plt 

df = nutri_app

for elem in ['energy_100g', 'sugars_100g','fat_100g','proteins_100g']:
#Create barplot
    fig, ax = plt.subplots(figsize=(30,6))
    sns.barplot(x="pnns_group1", y=elem, hue="nutrition_grade_fr", data=df)

#Add title
    ax.set_title(f"nutriscore by categories related to {elem} quantity variable")

#Show plot
    plt.show()
cqoc49vn

cqoc49vn1#

您需要pandas.DataFrame.sort_values并选择color palette(例如,蓝调):

import seaborn as sns
import matplotlib.pyplot as plt 

df = nutri_app.sort_values(by='nutrition_grade_fr') #ascending=True by default

for elem in ['energy_100g', 'sugars_100g','fat_100g','proteins_100g']:
#Create barplot
    fig, ax = plt.subplots(figsize=(30,6))
    sns.barplot(x="pnns_group1", y=elem, hue="nutrition_grade_fr", data=df, palette='Blues')

#Add title
    ax.set_title(f"nutriscore by categories related to {elem} quantity variable")

#Show plot
plt.show();

相关问题