0

I have been trying to plot two random numpy array but I'm not geeting line. Below is my code:

import numpy as np
import matplotlib.pyplot as plt

# Decalring numpy array variable
a = np.random.randint(2, 10, size=(1, 10))
b = np.random.randint(5, 15, size=(1, 10))

# plotting
plt.title("Line graph")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.plot(a, b, color ="green", label="Sample Line", marker="*")
plt.show()

Can anyone Explain me why its not printing line and show correct code?

1
  • 1
    Replace size=(1, 10) with size=(10, ) and also I hope you realize that you are plotting a as X and b as Y, and not plotting a and b as Y with one point per index (and thus range(10) as X). Commented Jul 11, 2022 at 12:44

1 Answer 1

1

If you have a look at the shapes of a and b, you'll find they both have a shape of (1, 10).

a = np.random.randint(2, 10, size=(1, 10))
b = np.random.randint(5, 15, size=(1, 10))
print(a.shape)
print(b.shape)

Matplotlib sees this as many "lines", each "line" with just one point! What you want is a single line with 10 points, so a and b should have a shape of (10,) instead.

The following code the above issue:

import numpy as np
import matplotlib.pyplot as plt

# Decalring numpy array variable
a = np.random.randint(2, 10, 10)
b = np.random.randint(5, 15, 10)

# plotting
plt.title("Line graph")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.plot(a, b, color ="green", label="Sample Line", marker="*")
plt.show()

But the result is as follows:

Here we have plotted a as the coordinates of points on the x-axis, and b as the coordinates of the line on the y-axis. Perhaps you wanted two lines that are continuous along the x-axis? If so, the following code will solve this:

import numpy as np
import matplotlib.pyplot as plt

# Decalring numpy array variable
a = np.random.randint(2, 10, 10)
b = np.random.randint(5, 15, 10)
xAxis = np.arange(10)

# plotting
plt.title("Line graph")
plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.plot(xAxis, a, color ="red", label="Sample Line", marker="*")
plt.plot(xAxis, b, color ="blue", label="Sample Line", marker="*")
plt.show()

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.