gpt4 book ai didi

python - Python 中具有正值和负值的堆积面积图

转载 作者:行者123 更新时间:2023-12-01 08:54:24 25 4
gpt4 key购买 nike

我想做一个堆积面积图,其中一些组为正,因此将出现在 x 轴上方(堆积),而其他组为负,因此将出现在 x 轴下方。目前,当我执行 stackplot 时,它只是添加实际值,因此具有负值的组不会出现在图中,但所有其他区域都会下移。基本上我想组合两个面积图,一个用于 x 轴上方的正组,另一个用于 x 轴下方的负组。

最佳答案

假设您有一个 pandas DataFrame df,其中组作为列,那么可以执行以下操作:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# split dataframe df into negative only and positive only values
df_neg, df_pos = df.clip(upper=0), df.clip(lower=0)
# stacked area plot of positive values
df_pos.plot.area(ax=ax, stacked=True, linewidth=0.)
# reset the color cycle
ax.set_prop_cycle(None)
# stacked area plot of negative values, prepend column names with '_' such that they don't appear in the legend
df_neg.rename(columns=lambda x: '_' + x).plot.area(ax=ax, stacked=True, linewidth=0.)
# rescale the y axis
ax.set_ylim([df_neg.sum(axis=1).min(), df_pos.sum(axis=1).max()])

关于python - Python 中具有正值和负值的堆积面积图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872938/

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