rutvik
rutvik

Reputation: 23

Plot area getting cropped out in the final graph using matplotlib

I am trying to draw a continuous plot with the last 10 data points from the dataset

from time import sleep
import matplotlib.pyplot as plt
#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
l1,= plt.plot([])
a=[]
if 1:
    count=4
    while True:
        x=count%4
        count+=1
        print x
        ls1.append(x)
        l1.set_data(range(10),ls1[-10:])

        #ax.set_xlim(-2,12)?
        #ax.set_ylim(0,5)? this throws error as ax is not defined and I am unable to define it

        plt.draw()
        plt.pause(0.5)
        
        #plt.show()
        sleep(0.5)

Output graph As you can see, the output graph's axes are limited in the range [-0.06,+0.06] whereas my output has xlim=[0,10] and ylim=[0,4]. How do I implement those limits to get the correct graph?

Upvotes: 0

Views: 372

Answers (2)

Luigi Favaro
Luigi Favaro

Reputation: 361

You can define a figure and then use the axes commands. This is a possible solution:

from time import sleep
import matplotlib.pyplot as plt

#plt.ion()
ls1 = [0,0,0,0,0,0,0,0,0,0]
fig = plt.figure() # define a Figure
ax = fig.gca()    # get the ax
l1,= ax.plot([])
a=[]
if 1:
    count=4
    while True:
        x=count%4
        count+=1
        print(x)
        ls1.append(x)
        l1.set_data(range(10),ls1[-10:])

        ax.set_xlim(-2,12) # now ax is defined
        ax.set_ylim(0,5) 

        plt.draw()
        plt.show()
        plt.pause(0.5)

        sleep(0.5)

Upvotes: 0

Whole Brain
Whole Brain

Reputation: 2167

ax often refers to the variable where we put the Axe(s) of a plot.

fig, ax = plt.subplots()
#or:
ax = plt.gca()

You didn't declare it in your code. Check here the subplots() method.

To force the x and y boundaries, you can either do:

fig, ax = plt.subplots()
ax.plot(range(10), ls1[-10:])
ax.set_xlim(0,10)
ax.set_ylim(0,4)
# ...
plt.show()

... or:

plt.plot(range(10), ls1[-10:])
plt.xlim(0, 10)
plt.ylim(0, 4)
# ...

Upvotes: 1

Related Questions