2012-06-17 79 views
1

我有一个生成简单2D图表的matplotlib代码。我想为hte和hre变量(这是数组)添加滑块小部件,以便交互式地增加或减少hte和hre值。有没有一种方法(我确信这是因为我在matplotlib网站上看到了这样的something,但我无法将其与我的代码集成)?任何帮助将不胜感激。下面是代码:将滑块添加到matplotlib图表

from mpl_toolkits.mplot3d import Axes3D 
from matplotlib import cm 
from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter 
import matplotlib.pyplot as plt 
import numpy as np 
from pylab import * 

hte=np.array([10,11,12,13,15,20,21,22,25,30]) 
hre=np.array([1,2,3,4,5,6,7,8,9,10]) 

k=20*hte 
n4=10*hre 
t=6 
w4=25 

x=arange(1,100,10) 
d=(log(x)/log(10))/10 
y= k + n4 * (d) + t + w4 + 8 

matplotlib.pyplot.jet() 
lines=plot(x,y) 
setp(lines, linewidth=2, color='r') 
xlabel('X - Title') 
ylabel('Y - title') 
title('$Our Chart$') 
grid(True) 
show() 

here is the chart that it generates

+0

你将如何改变与滑块值的数组中的值。你能举一个例子吗? – joaquin

+0

就像,例如,两个滑块将简单地滑过它们各自的离散数组值。甚至,我可以为hte和hre声明一个公式。没什么大不了的,但只是为了向你们展示,我把它作为一个理想的数组提及。 – khan

+0

@joaquin你能帮我解决类似的问题吗? http://stackoverflow.com/questions/43381449/how-to-make-two-sliders-in-matplotlib – Hana

回答

5

按照你的意见,我选择的滑块,他们乘阵列中的值的方法。你应该应用你的特定算法。

from pylab import * 
from matplotlib.widgets import Slider 
import numpy as np 

hte = np.array([10, 11, 12, 13, 15, 20, 21, 22, 25, 30]) 
hre = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) 

k = 20 * hte 
n4 = 10 * hre 
t, w4 = 6, 25 
x = arange(1, 100, 10) 
d = log10(x)/10 

y = k + n4 * d + t + w4 + 8 

ax = subplot(111) 
subplots_adjust(left=0.15, bottom=0.25) 
line, = plot(x, y, linewidth=2, color='r') 

xlabel('X - Title') 
ylabel('Y - title') 
title('$Our Chart$') 
grid(True) 

axcolor = 'lightgoldenrodyellow' 
axhte = axes([0.15, 0.1, 0.65, 0.03], axisbg=axcolor) 
axhre = axes([0.15, 0.15, 0.65, 0.03], axisbg=axcolor) 

shte = Slider(axhte, 'hte', 0.1, 30.0, valinit=1) 
shre = Slider(axhre, 'hre', 0.1, 10.0, valinit=1) 

def update(val): 
    k = 20 * hte * shte.val 
    n4 = 10 * hre * shre.val 

    y= k + n4 * d + t + w4 + 8 

    line.set_ydata(y)  
    ax.set_ylim(y.min(), y.max()) 
    draw() 

shte.on_changed(update) 
shre.on_changed(update) 

show() 

enter image description here

+0

joaquin,兄弟,两个字:你的规则! :-)现在一件小事......增加和减少滑块实际上是递增和递减hte和hre的值?另外,当你在滑块中定义0.1到30和0.1到10的极限时,它究竟做了什么?需要一点点这个,请。 – khan

+1

移动滑块可以获得不同的值(在滑块右侧指示)。这些值可以从'shre.val'和'shte.val'中读取。我使用这些变量来将你的hte和hre数组放在'update'中。我指定滑块中的最小值和最大值(0.1至30和0.1至10)。你可以选择你需要的任何限制。 – joaquin

+0

再次感谢你,兄弟。我会将你的逻辑合并到我的代码中,并将其发布在此处..我还有其他一些有趣的问题,我将在今天发布。 :-)再一次非常感谢你。你是一个拯救生命的人。 – khan