问题
Hey I am trying to create a scatter plot with a slider that updates the plot as I slide across. This is my code so far. It draws a scatter plot and a slider but as I move it around, nothing happens. I suspect that the problem is with the .set_ydata
bit but I can't seem to find how to do it otherwise on the Internet.
import numpy as np
from matplotlib.widgets import Slider
from pylab import plot, show, figure, scatter, axes, draw
fig = figure()
ax = fig.add_subplot(111)
x, y = np.random.rand(2,100)
scat = scatter(x,y)
axcolor = 'lightgoldenrodyellow'
axamp = axes([0.2, 0.01, 0.65, 0.03], axisbg=axcolor)
scorr = Slider(axamp, 'corr', -2,2, valinit=1)
def update(val):
corr = scorr.val
for i in range(len(x)):
x[i]=x[i]+corr*np.random.randn()
for i in range(len(y)):
y[i]=y[i]+corr*np.random.randn()
scat.set_xdata(x)
scat.set_ydata(y)
draw()
scorr.on_changed(update)
show(scat)
This is just a test script in fairness. I have to do the same thing with a much more complicated script but realized it would be easier to try it out on a simpler problem. I really just care about scat.set_ydata
and what to put there instead so that it works.
Thanks in advance.
回答1:
You need to use set_offsets
and set_array
in stead:
# make sure you get the right dimensions and direction of arrays here
xx = np.vstack ((x, y))
scat.set_offsets (xx.T)
# set colors
scat.set_array (y)
Probably duplicate of: How to animate a scatter plot?
来源:https://stackoverflow.com/questions/38368990/scatter-plot-with-a-slider-in-python