循环累加线性图的结果

时间:2018-06-02 16:12:57

标签: python list loops matplotlib

我一直试图解决这个困难几天,但由于我的理解有限,没有运气。任何见解都会非常明显。

基本上,我有一个循环。当我绘制结果时,它会相互叠加。 enter image description here

然而,我想要它线性地绘制它们。像这样的东西。 enter image description here

我目前的代码如下。感谢您的帮助。

import numpy as np
rate           = 0.07
saving         = 2000
year           = [1, 2, 4, 6]

for x in year:
    month          = np.arange(1,12*x+1,1)
    compound       = (1+rate/12)**month
    monthly_saving = saving*np.ones(np.size(month))
    monthly_growth = compound*monthly_saving
    total_growth = np.cumsum(monthly_growth)

    import itertools
    list2d = [total_growth]
    merged = list(itertools.chain(*list2d))

    import matplotlib.pyplot as plt
    plt.plot(np.arange(1,np.size(merged)+1)/12, merged)

plt.xlabel("year")
plt.ylabel("asset")
plt.show()

1 个答案:

答案 0 :(得分:0)

固定系列

import numpy as np
#  import itertools
import matplotlib.pyplot as plt


rate           = 0.07
saving         = 2000
year           = [1, 2, 4, 6]

merged = []                                      # init merge
for x in year:
    month          = np.arange(1,12*x+1,1)
    compound       = (1+rate/12)**month
    monthly_saving = saving*np.ones(np.size(month))
    monthly_growth = compound*monthly_saving
    total_growth = np.cumsum(monthly_growth)

    list2d = list(total_growth)                  # convert tolist
    merged.extend(list2d)                        # extend list

plt.plot(np.arange(1,len(merged)+1)/12, merged)  # plot once

plt.xlabel("year")
plt.ylabel("asset")
plt.show()