[英]Color of bar in chart based off boolean value in the same row of dataframe
I'm Trying to construct a bar chart with the colour of the bars being influenced from the boolean value on the same row in the dataframe.我正在尝试构建一个条形图,条形图的颜色受 dataframe 中同一行上的 boolean 值的影响。 In this example I'm wanting
has_chocolate
with False
to be red and True
to be green when sales
are put in a bar chart.在此示例中,当
sales
放入条形图中时,我希望带有False
的has_chocolate
为红色, 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
What I've attempted so far with using an outside function or a condition到目前为止,我尝试使用外部 function 或条件
cake_sales_df.plot(x='cake', y='sales',
kind='bar', color = 'green' if cakes_sales_df['has_chocolate'] == True else 'red')
have all gotten me the same error都给了我同样的错误
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
I was able to use matplotlib to make a bar chart.我能够使用 matplotlib 制作条形图。 But due to the lack of reputation the picture is not embedded.
但由于缺乏声誉,图片没有嵌入。 Instead the links to imgur are provided.
相反,提供了指向 imgur 的链接。
import pandas as pd
from matplotlib.patches import Patch
columns = ['cake', 'sales', 'has_chocolate']
df = pd.DataFrame([['empire', 15, False],['tea cake',25, True],['snowball', 20, True],['hob-nob', 50, True],['lotus', 3, False]], columns = columns).set_index('cake')
df
colours = {True: "#44bd32", False: "#273c75"}
df['sales'].plot(
kind="bar",
color=df['has_chocolate'].replace(colours)
).legend(
[ Patch(facecolor=colours[True]),
Patch(facecolor=colours[False])
], [True, False]
)
You can pivot the data:你可以pivot的数据:
(df.pivot(index='cake',columns='has_chocolate',values='sales')
.plot.bar(stacked=True)
)
Output: Output:
Or you can use seaborn:或者您可以使用 seaborn:
import seaborn as sns
sns.barplot(data=df, x='cake', y='sales', hue='has_chocolate',
palette={True:'g', False:'r'},
dodge=False)
Output: Output:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.