我正在尝试构建一个条形图,其中条形的颜色受数据框中同一行上 bool 值的影响。在这个例子中,当 sales
被放置时,我希望 has_chocolate
和 False
是红色的,True
是绿色的在条形图中。
import pandas as pd
import matplotlib.pyplot as plt
cake_sales_df
index cake sales has_chocolate
0 empire 15 False
1 tea cake 25 True
2 snowball 20 True
3 hob-nob 50 True
4 lotus 3 False
到目前为止我尝试使用外部函数或条件
cake_sales_df.plot(x='cake', y='sales',
kind='bar', color = 'green' if cakes_sales_df['has_chocolate'] == True else 'red')
我都犯了同样的错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
最佳答案
您可以旋转数据:
(df.pivot(index='cake',columns='has_chocolate',values='sales')
.plot.bar(stacked=True)
)
输出:
或者你可以使用seaborn:
import seaborn as sns
sns.barplot(data=df, x='cake', y='sales', hue='has_chocolate',
palette={True:'g', False:'r'},
dodge=False)
输出:
关于python - 图表中条形图的颜色基于数据框同一行中的 bool 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65008989/