2

I generated two arrays with 10 different values. How do I plot 3 specific values within each array using matplotlib? Here is my code so far:

import numpy as np
import matplotlib as plt
x = np.array(1,2,3,4,5,6,7,8,9,10)
y = np.array(1,2,3,4,5,6,7,8,9,10)

I only want to plot the points 3,4,5 of the x-array and it's corresponding y values. I have tried this:

plt.plot(x[2,3,4], y[2,3,4])
plt.show()

But I get the error "too many indices for array." However, if I write

plt.plot(x[2], y[2])
plt.show()

the second element in the arrays will plot.

4
  • 4
    Try: x = np.array(1,2,3,4,5,6,7,8,9,10) --> x = np.array([1,2,3,4,5,6,7,8,9,10]) the same for y. And in plot: x[2:5], y[2:5] Commented Mar 7, 2017 at 21:34
  • I think you also want to import the pyplot submodule: import matplotlib.pyplot as plt. Commented Mar 7, 2017 at 22:02
  • Thanks a lot! How do I do this if I wanted to only plot 3 different random elements in each array? For my actual data, the elements are not are in order from least to greatest Commented Mar 7, 2017 at 22:39
  • Then instead of plotting x[2,3,4], you can type x[np.array([2,3,4])] ! If x is a numpy array you can select elements with a another numpy array :) Commented Mar 8, 2017 at 15:39

1 Answer 1

5

The problem is the syntax of x[3, 4, 5]. It is wrong what you want to do is x[3], x[4], x[5], which are the respective elements of the array.

print(x[3], x[4], x[5]) # print 4, 5, 6

A more comfortable way to do this is:

plt.plot(x[2:5], y[2:5])
plt.show()

Where x[2:5] returns from the third to the fifth element.

As Tony Tannous says, the creation of the array is also wrong. np.array needs a list!

Then you also have to change the creation of x and y:

x = np.array([1,2,3,4,5,6,7,8,9,10])
y = np.array([1,2,3,4,5,6,7,8,9,10])

Adding [ and ] to make it a list.

Surely you should see the documentation of Indexing

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

1 Comment

You still have to wrap the array elements by [] in np.array. docs.scipy.org/doc/numpy/reference/generated/numpy.array.html

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.