Home > Net >  What is the meaning of indexing in plt.plot()
What is the meaning of indexing in plt.plot()

Time:11-26

I am learning about matplotlib and found code : plt.plot([])[0]. Can u explain what means of index on that code?

Im trying to make animation using matplotlib and one of the example using that code. I dont understand the meaning of index in that code

CodePudding user response:

lets say you plot multiple lines with plt.plot, e.g. like this

import numpy as np
from matplotlib import pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

enter image description here

you can use the index after plt.plot() for retrieving each single Line2D object, eg. like this

line1 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[0]
line2 = plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')[1]

and then interact with the single Line2D object, for example with

x1, y1, = line1.get_data()

for more methods see https://matplotlib.org/stable/api/_as_gen/matplotlib.lines.Line2D.html

  • Related