python - Matplotlib 填充权重步骤图

标签 python pandas numpy matplotlib

我有一个 DataFrame,其中包含 N 个项目的重量值的历史记录。所有项目的权重之和为 1。该日期是设置权重的日期,并且在再次设置之前它们保持不变。

这是数据框。

            item2     item3     item4     item1
2018-03-26  0.333331  0.333331  0.000008  0.333331
2018-03-29  0.097470  0.249645  0.250353  0.402532
2018-04-01  0.329531  0.080273  0.356974  0.233221
2018-04-04  0.279514  0.048366  0.288980  0.383140
2018-04-07  0.289597  0.082032  0.201930  0.426442
2018-04-10  0.258850  0.107432  0.280754  0.352964
2018-04-13  0.030390  0.172697  0.486147  0.310766
2018-04-16  0.019628  0.095833  0.433445  0.451094
2018-04-19  0.054276  0.270346  0.351813  0.323565
2018-04-22  0.075713  0.089441  0.385883  0.448963
2018-04-25  0.109152  0.071784  0.536841  0.282223
2018-04-28  0.172047  0.108976  0.360786  0.358192
2018-05-01  0.059381  0.072429  0.434918  0.433272

我想可视化权重如何随时间变化。我想出了这个。

#weight_history is the DataFrame
tot = np.zeros(len(weight_history))
for weight in weight_history:
    plt.step(weight_history[weight].index, weight_history[weight].values+tot,where='post',label=weight)
    tot += weight_history[weight].values
plt.set_ylabel("Weights")
plt.legend()

这会产生这个:

enter image description here

这非常接近我想要的,但很难想象每件元素有多少重量。

如何填写每行下方的区域?

所以从0到蓝线填充蓝色,从蓝线到橙线填充橙色,从橙线到绿线填充绿色,从绿线到红线填充红色。

有其他方法可以做到这一点吗?

最佳答案

我明白了,fill_between有一个步骤选项。

tot = np.zeros(len(weight_history))
for weight in weight_history:
    axes[1].fill_between(x=weight_history.index, y1=weight_history[weight].values+tot,y2=tot,step='post',label=weight)
    tot += weight_history[weight].values
axes[1].set_ylabel("Weights")
axes[1].legend()

关于python - Matplotlib 填充权重步骤图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50226332/

相关文章:

python - 计算几何级数上三角矩阵的最快方法(Python)

python - 如何在Python POST请求中发送原始数据

python - 如何运行长期(无限)Python 进程?

python - 使用 urllib 2 捕获错误 60(超时)

python - 合并时间戳大于或等于的数据帧

python - Pandas 中的条件求和

python - 如何使用 Python 检查时间窗口中是否存在某些值

python - numpy.loadtxt 分析结果的差异

python - 使用正则表达式替换 Pandas 数据框中字符串的特定部分

python - 在 Fedora 24 上的 Python3 中使用 `cairo.Region` 时出现段错误