gpt4 book ai didi

python - 如何为 pandas 条形图上的负值和正值着色?

转载 作者:太空宇宙 更新时间:2023-11-03 14:50:12 24 4
gpt4 key购买 nike

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
from datetime import datetime
import seaborn as sns
import matplotlib.pyplot as plt
import mpld3

# Set some pandas options
pd.set_option('display.notebook_repr_html', False)
pd.set_option('display.max_columns', 10)
pd.set_option('display.max_rows', 10)

# seaborn settings
sns.set_palette("deep", desat=.6)
sns.set_context(rc={"figure.figsize": (8,4)})
# And some items for matplotlib
%matplotlib inline

# plt.style.available
plt.style.use('seaborn')
# mpld3.enable_notebook()
gp = df.groupby(['year','department', 'worktype']).agg({'minutes':'sum'})
df1 = gp.loc[2016]
df2 = gp.loc[2017]
diff = (df2-df1).dropna()
diff['positive']=diff['minutes'] > 0
print(diff)
diff.plot(kind='bar', color=diff.positive.map({True: 'b', False: 'y'}))
plt.show()
<小时/>

我的差异数据集

                    minutes  positive
department worktype
TA PHP 0.0 False
PYTHON -100.0 False
WEB ANDROID 5.0 True
PYTHON -410.0 False

enter image description here

最佳答案

您可以将 lambda 函数应用于颜色参数。

import pandas as pd
%matplotlib inline

df=pd.DataFrame({'department':['TA','TA','WEB','WEB'],
'worktype':['PHP','PYTHON','ANDROID','PYTHON'],
'minutes':[0.0,-100.0,5.0,-410.0]})\
.set_index(['department', 'worktype'])
df.plot(kind='bar',
color=df.minutes.apply(lambda x: 'b' if x>0 else 'y'));

关于python - 如何为 pandas 条形图上的负值和正值着色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45929742/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com