将滑块添加到Matplotlib图表 [英] Add slider to matplotlib chart

查看:294
本文介绍了将滑块添加到Matplotlib图表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个matplotlib代码,可以生成简单的2D图表.我想向其中添加用于hte和hre变量(它们是数组)的滑块部件,以便可以交互地增加或减少hte和hre值.有没有办法(我确定是有原因的,因为我已经看过类似的东西在matplotlib网站上显示此信息,但我无法将其与我的代码集成)?任何帮助将不胜感激.这是代码:

I have a matplotlib code that generates a simple 2D chart. I want to add sliders widget to it for hte and hre variables (which are arrays) so that hte and hre values can be increased or decreased interactively. Is there a way (I am sure there is because I have seen something like this on matplotlib website but I am not able to integrate it with my code)? Any help will be appreciated. Here is the code:

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()

推荐答案

在您发表评论之后,我选择了将滑块与数组中的值相乘的方式.您应该应用自己的特定算法.

Following your comment, I selected sliders in a way they multiply the values in the arrays. You should apply your particular algorithm.

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()

这篇关于将滑块添加到Matplotlib图表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆