0

Can someone explain why I get this strange output when running this code:

import matplotlib.pyplot as plt
import numpy as np
def x_y():
    return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
plt.plot(x_y())
plt.show()

The output:

Output of the program

2 Answers 2

1

Your data is a tuple of two 1000 length arrays.

def x_y():
    return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
xy = x_y()
print(len(xy))
# > 2
print(xy[0].shape)
# > (1000,)

Let's read pyplot's documentation:

plot(y) # plot y using x as index array 0..N-1

Thus pyplot will plot a line between (0, xy[0][i]) and (1, xy[1][i]), for i in range(1000).

You probably try to do this:

plt.plot(*x_y())

This time, it will plot 1000 points joined by lines: (xy[0][i], xy[1][i]) for i in range 1000.

Pyplot

Yet, the lines don't represent anything here. Therefore you probably want to see individual points:

plt.scatter(*x_y())

Scatter

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

Comments

0

Your function x_y is returning a tuple, assigning each element to a variable gives the correct output.

import matplotlib.pyplot as plt
import numpy as np
def x_y():
    return np.random.randint(9999, size=1000), np.random.randint(9999, size=1000)
x, y = x_y()
plt.plot(x, y)
plt.show()

enter image description here

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.