Plotting a basic vectorized function

时间:2016-02-03 03:00:20

标签: python python-3.x numpy matplotlib

I am trying to get my function to plot a vectorized function over a python list interval and having a name/title for the graph. I am fairly new to python packages like numpy and matplotlib. I hope someone can shed some light on my code:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline    

def test_plot(x,interval,title):
    x = np.vectorize(x)
    interval = [0,interval+1]
    ttl = plt.title(title)
    plt.plot(x,interval)
    return plt.plot(x,interval)    

test_plot([-1,0,1,2,3,4],2,'test')

I get this error:

ValueError: x and y must have same first dimension

Note: I need the interval to be a list.

2 个答案:

答案 0 :(得分:1)

I don't quite understand what you are going to plot.

After checking the document , you can find :

numpy.vectorize requires a pyfunc to be initialized .

For example :

>>> def myfunc(a, b):
...     "Return a-b if a>b, otherwise return a+b"
...     if a > b:
...         return a - b
...     else:
...         return a + b

Then initiate your vectorize function

>>>vfunc = np.vectorize(myfunc)
>>>vfunc([1, 2, 3, 4], 2)
array([3, 4, 1, 2])

The parameter pyfunc must be callable . Passing a list seems meaningless .

As for matplotlib.pyplot.plot.

This function require x and y to have same dimension to be plotted .

But what your pass is a function and two elements list causing a ValueError

答案 1 :(得分:0)

Like KIDJournety, I don't quite understand what you're wanting either, but if I understand your comments correctly this might work:

def test_plot(x, interval, title): import matplotlib.pyplot as plt plt.title(title) plt.plot(x, interval) plt.show()

test_plot([1,2,3], [7,6,5], "hello, world!") works well. If this doesn't do what you need (what with the vectorisation) please comment below and I'll do my best to adjust the code accordingly.

Now for some practical reasons why your original code did not work: You were passing a list or vector with 6 elements (-1 through 4) as the x-values of the graph, but only 2 elements(0 and interval+1, which was 3 in your example) as your y-values. Your poor code could only pair (-1, 0) and (0,3). The rest of the x-coordinates had no corresponding y-coordinates to be paired to, so the code failed.

相关问题