R_M*_*ter 4 python matplotlib stacked-area-chart pandas
我想做一个堆叠面积图,其中一些组为正,因此将出现在 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()])
Run Code Online (Sandbox Code Playgroud)