Python script does not generate the graph as expected

0

My algorithm in Python is running perfectly, I just can not generate the graph! I could not identify the error ... What's wrong?

import matplotlib.pyplot as plt

va=float(input('Digite o valor a ser aplicado: '))
juros=1.05
inflacao=1.02
saque=25000
vaplicacao=[va]
nsaque=0
vsaque=[]

while saque<=vaplicacao[len(vaplicacao)-1]:
    va=(vaplicacao[len(vaplicacao)-1]*juros)-(saque)
    vaplicacao.append(va)
    nsaque=nsaque+1
    saque=saque*inflacao
    vsaque.append(nsaque)

plt.plot(vsaque,vaplicacao,'b-')
plt.title('Saldo x Saque')
plt.grid(True)
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')
plt.show()
    
asked by anonymous 06.06.2018 / 20:52

2 answers

0

In your case, since the draw count is linear and sequential, you do not need to build a list for the X-axis of the chart. matplotlib is able to do this automatically, and your program could get more compact, see:

import matplotlib.pyplot as plt

va = float(input('Digite o valor a ser aplicado: '))

juros = 1.05
inflacao = 1.02
saque = 25000
vaplicacao = [va]

while saque <= vaplicacao[-1]:
    va = (vaplicacao[-1] * juros) - saque
    saque *= inflacao
    vaplicacao.append(va)

plt.plot( vaplicacao, 'b-')
plt.plot( vaplicacao, 'ro')

plt.grid(True)
plt.title('Saldo x Saque')
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')

plt.show()

Output (% with%):

Output(%with%):

Output(%with%):

    
06.06.2018 / 22:40
0

You are initializing the vaplicacao list with a value:

vaplicacao=[va]

While the vsaque list starts empty:

vsaque=[]

Since, within the loop, you always add a value to each list, the vaplicacao always list will have one element more than vsaque ; so it is impossible to plot a curve on a graph that has% with% points on the abscissa axis and% with% points on the ordinate axis. If you start n with a value it will possibly work:

vsaque=[nsaque]

Incidentally, to get the last element of the list, just do n+1 ; does not need vsaque .

import matplotlib.pyplot as plt

va = float(input('Digite o valor a ser aplicado: '))
juros = 1.05
inflacao = 1.02
saque = 25000
vaplicacao = [va]
nsaque = 0
vsaque = [nsaque]

while saque <= vaplicacao[-1]:
    va = vaplicacao[-1]*juros - saque
    vaplicacao.append(va)
    nsaque += 1
    saque = saque*inflacao
    vsaque.append(nsaque)

plt.plot(vsaque, vaplicacao, 'b-')
plt.title('Saldo x Saque')
plt.grid(True)
plt.xlabel('Saque ao longo dos anos')
plt.ylabel('Saldo ao longo dos anos')
plt.show()
    
06.06.2018 / 21:17