Python中带正负值的堆积面积图

2024-04-18 21:40:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个堆积面积图,其中一些组是正的,因此将出现在x轴上方(堆叠),而其他组是负的,因此将出现在x轴下方。在我做stackplot的时候,它只是将实际值相加,这样在中有负值的组不会出现在绘图中,而是所有其他区域都向下移动。基本上我想合并两个面积图,一个是x轴上的正组,一个是x轴下的负组。在


Tags: 区域绘图面积负值stackplot
2条回答

{pandas}可以像cd1>那样,用一个像cd1这样的数据框来做:

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 3.7/Windows 10/Spyder IDE:

import matplotlib.pyplot as plt

x_axis = [1,2,3,4,5,6,7,8,9,10]
cheap = [-5,-4,-6,-8,-4,-2,-4,-8,-7,-3]
expensive = [3,4,8,7,9,6,4,3,2,3]


fig_size = plt.rcParams["figure.figsize"] #set chart size (longer than taller)
fig_size[0] = 39
fig_size[1] = 10
plt.rcParams["figure.figsize"] = fig_size
plt.rcParams.update({'font.size': 18}) 

plt.stackplot(x_axis, expensive, colors=['r'])
plt.stackplot(x_axis, cheap, colors=['g'])

plt.plot([],[],color='r', label='Above great case', linewidth=5)
plt.plot([],[],color='g', label='Below low case', linewidth=5)
plt.legend()

plt.xlabel('Years')
plt.ylabel('Number of companies')
plt.title('Under/over valuation over time')
plt.show()

您应该看到的图表: enter image description here

这个例程实际上是用来绘制一个包含数千个x轴数据点的图表。我在条形图之前试过了,它比这个面积图要花更长的时间。以下是制作的真实图表示例:

enter image description here

相关问题 更多 >