1

I'm trying to simplify my code. The code is meant to draw some diagonal lines on a graph. The following is the original code:

x = np.linspace(-5,6,50)
y1 = x
y2 = x+1
y3 = x+2
y4 = x+3
y5 = x+4
y6 = x-1
y7 = x-2
y8 = x-3
y9 = x-4

plt.plot(x,y1, linewidth=3, color='k')

plt.plot(x,y2, color='b')
plt.plot(x,y3, color='b')
plt.plot(x,y4, color='b')
plt.plot(x,y5, color='b')
plt.plot(x,y6, color='b')
plt.plot(x,y7, color='b')
plt.plot(x,y8, color='b')
plt.plot(x,y9, color='b')

I'm trying to simplify the last few lines with the following 'for' loop:

for i in np.arange(2,10):
    plt.plot(x,yi, color='b')

the i is not recognized by Python. What would be the correct way to do this? Perhaps a lambda? I'm really not sure.

Yehuda
  • 1,787
  • 2
  • 15
  • 49
  • 2
    Putting your `y` values in a list is probably simplest, then you can `plt.plot(x,y[i], color='b')` – Nick Jan 05 '20 at 00:40
  • 1
    Related to your attempted solution: [How do I create a variable number of variables?](https://stackoverflow.com/q/1373164/4518341) If you went that route you would want to use a list. But I think [gmds's answer](https://stackoverflow.com/a/59596113/4518341) makes more sense in this case. – wjandrea Jan 05 '20 at 00:42

1 Answers1

1

Use a simple for loop:

plt.plot(x, x, lw=3, color='k')

for i in range(-4, 5):
    if i != 0:
        plt.plot(x, x + i, color='b')
gmds
  • 19,325
  • 4
  • 32
  • 58