在python中使用滑块进行散点图 [英] Scatter plot with a slider in python
问题描述
嘿,我正在尝试使用一个滑块创建散点图,该滑块会在我滑过时更新该图.到目前为止,这是我的代码.它绘制了一个散点图和一个滑块,但是当我四处移动时,什么也没有发生.我怀疑问题出在 .set_ydata
位,但在Internet上我似乎找不到解决方法.
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)
这只是一个公平的测试脚本.我必须使用更复杂的脚本来做同样的事情,但意识到在一个更简单的问题上尝试起来会更容易.我真的只是在乎 scat.set_ydata
以及放置在其中的内容,以便它起作用.
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.
谢谢.
推荐答案
您需要改为使用 set_offsets
和 set_array
:
# 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?
这篇关于在python中使用滑块进行散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!