Home > Blockchain >  How to make matplotlib auto scale y axis when using the draw_artist?
How to make matplotlib auto scale y axis when using the draw_artist?

Time:10-03

I have the follow sample code:

import matplotlib.pyplot as plt

# start with zeroed data

data_points = 10

fig, axs = plt.subplots()
x = list(range(data_points))
y = [0] * data_points
line, = axs.plot(x, y)

# initial render is required
fig.canvas.draw()

for i in range(10):
    y.pop(0)
    y.append(i / 10)

    line.set_ydata(y)
    axs.draw_artist(axs.patch)
    axs.draw_artist(line)

    fig.canvas.draw()

plt.show()

This simulates what I do in my app: I have a zeroed out data set, then I append values to the y data and redraw using the draw_artist.

I see here that the end result is what I get in my real app: the Y axis is scaled to fit the data that was appended to the y:

enter image description here

Y should end up going from 0 to 0.9, but it's stuck at what it looked like when the data was first drawn zeroed out.

How can I make the y axis update correctly in the sample above?

CodePudding user response:

Here you go the updated version of your code, you can achieve that by defining the ylim.

import matplotlib.pyplot as plt
import numpy as np

# start with zeroed data

data_points = 10

fig, axs = plt.subplots()
x = list(range(data_points))
y = [0] * data_points
line, = axs.plot(x, y)

# initial render is required
fig.canvas.draw()

for i in range(10):
    y.pop(0)
    y.append(i / 10)

    line.set_ydata(y)
    axs.draw_artist(axs.patch)
    axs.draw_artist(line)

    fig.canvas.draw()
plt.ylim(np.min(y),np.max(y))

plt.show()

This is what you will get:

enter image description here

  • Related