1

This may sound like a very naive question. However, to me, it's quite fundamental: Can python plot variables without putting them into arrays or lists? I couldn't find much answer on the net or SO and please let me know if there's any duplicate.

I have the following code for demonstration:

import matplotlib.pyplot as plt
import numpy as np

x = 0.0
dx = 0.5

for i in range(10):
    y = x**2
    plt.plot(x,y)
    x += dx

plt.show()


x = np.linspace(-0,.5,10)
y = x**2
plt.plot(x,y)
plt.show()

The first part doesn't plot (which is in an explicit for-loop) anything while the second part does (where both x and y are numpy arrays).

Is it possible to plot without storing variables in arrays or lists? plt.scatter(x,y,c='r') works but that doesn't produce any line plot.

1
  • 4
    Why would you want to avoid using arrays or lists? Plotting implies that you have a bunch of data points, and trying to manage a bunch of data points without some kind of collection (e.g. an array or list) sounds like one of the lower circles of hell. You could write a plotting library that doesn't allow the caller to use lists, but nobody would want to use it. Commented May 12, 2022 at 22:12

1 Answer 1

1

Store the start and end of each segment to iteratively build a series of lines from datapoint to datapoint: (x0,y0) -> (x1, y1)

import matplotlib.pyplot as plt
import numpy as np

x0, y0 = 0, 0
x1 = 0.0
dx = 0.5

for i in range(10):
    y1 = x1**2
    plt.plot([x0,x1],[y0,y1], 'o-')
    x0, y0 = x1, y1
    x1 += dx

plt.show()

Lineplot

Note: this example will draw a line from (0,0) to (0,0) as the x1 value chosen is starting at 0.0

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.