Rhys Jones
Rhys Jones

Reputation: 53

Python pylab chart plot and loops

I'm just learning Python and I'm wondering if someone could help me get the chart to render properly in the following code, i.e. plot the sequence of data points. I have put print statements so I can see if the calculations are correct which they are.

Thanks

from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

ff = float(25)
for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    plot(dd,tt1)
    print(dd)
    print(tt1)
title("Something")
xlabel("x label")
ylabel("y label")
show()

Upvotes: 0

Views: 41

Answers (2)

foglerit
foglerit

Reputation: 8279

You can vectorize your function and work with NumPy arrays to avoid the for-loop and better inform matplotlib of what you want to plot

import numpy as np
from pylab import *

def some_function(ff, dd):
    if dd >=0 and dd <=200:
        tt = (22/-90)*ff+24
    elif dd >=200 and dd <=1000:
        st = (22/-90)*(ff)+24
        gg = (st-2)/-800
        tt = gg*dd+(gg*-1000+2)
    else:
        tt = 2.0
    return tt

vectorized_some_function = np.vectorize(some_function)

ff = float(25)
dd = np.linspace(0, 1100, 12)
tt = vectorized_some_function(ff, dd)
plot(dd, tt)
title("Something")
xlabel("x label")
ylabel("y label")
show()

plot

Upvotes: 1

Sheldore
Sheldore

Reputation: 39072

Since you are plotting one point at a time, you need either a scatter plot or a plot with markers

for dd in range (0, 1200, 100):
    tt1 = some_function(ff, dd)
    scatter(dd, tt1) # Way number 1
    # plot(dd,tt1, 'o') # Way number 2

enter image description here

EDIT (answering your second question in the comments below): Save the results in a list and plot outside the for loop

result = []
dd_range = range (0, 1200, 100)
for dd in dd_range:
    tt1 = some_function(ff, dd)
    result.append(tt1)
plt.plot(dd_range, result, '-o')   

enter image description here

Upvotes: 1

Related Questions