0

I am trying to make a pyplot graph, but my x and y values are of different length.

I am using numpy's arange function to create the range of x values based on the length of my list of y values.

def event_editor(EventDatabase, ConcatenatedEvents, ConcatenatedFits):

    for i in list(EventDatabase):

        # Check for events with absurd blockage current

        if abs(EventDatabase[i]['AllLevelFits'][0]) > 5:
            del EventDatabase[i]
            continue
        event = ConcatenatedEvents[i][0]
        fit = ConcatenatedFits[i]
        x_values = np.arange(0, len(event) / 100, .01)
        x_values2 = np.arange(0, len(fit) / 100, .01)

        fig = plt.figure()
        plt.plot(x_values, event, figure=fig)
        plt.plot(x_values2, fit, figure=fig)
        plt.xlabel('Time (ms)', figure=fig)
        plt.ylabel('Current (I)', figure=fig)
        plt.title('Event #' + str(i), figure=fig)
        plt.show()

I'd expect the x_values and the event/fit lists to have the same length, and most of the time they do have the same length. However, when the length of event/fit is 111, the length of the x_values is 112. What causes this?

1

1 Answer 1

2

This is due to float approximation in Python / NumPy. The inconsistent behavior is documented also in its official docs.

A more robust approach is to use: np.linspace() e.g.:

step = 0.01
np.arange(0, len(event) / 100, step)
np.arange(0, len(fit) / 100, step)

becomes, for example:

step = 0.01
N = int(max(len(event) / 100 / step, len(fit) / 100 / step))

np.linspace(0, len(event) / 100, N)
np.linspace(0, len(fit) / 100, N)

note that with np.linspace() you specify the number of points rather than the step as last parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.