如何解决Matplotlib窗口内回归线的输出值
import matplotlib.pyplot as plt
import numpy as np
x = np.array([6,15,24,33,41,52,59,66,73,81])
y = np.array([5,10,20,25,30,35,40,45,50])
coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef) # to create a linear function with coefficients
plt.plot(x,'ro',x,poly1d_fn(x),'-b')
plt.errorbar(x,yerr=poly1d_fn(x) - y,fmt='.k')
plt.show()
我有一个工作代码,根据我的输入生成带有误差线和回归线的图形。没关系的现在我想做的是在下面添加一个文本框,一旦用户输入了数字,例如12输出相应的值(回归线)。
left,bottom,width,height = 0.15,0.02,0.7,0.10
plt.subplots_adjust(left=left,bottom=0.25) # Make space for the slider
input_field = plt.axes([left,height])
box = TextBox(input_field,'value')
我用这种方法尝试过。虽然不成功:我无法获取它的值并将其输出到matplotlib提供的GUI接口上。每个输入都需要检查该字段。 Matplotlib提供on_text_change(self,func)
或on_submit(self,func)
,因此可能有效-但是如何输出?
有人有主意吗?
解决方法
我将使用一个简单的Text
艺术家来显示结果。但花哨的是,我还将在图形上显示显示输入和输出值的线。
import matplotlib.pyplot as plt
import numpy as np
x = np.array([6,15,24,33,41,52,59,66,73,81])
y = np.array([5,10,20,25,30,35,40,45,50])
coef = np.polyfit(x,y,1)
poly1d_fn = np.poly1d(coef) # to create a linear function with coefficients
def submit(val):
try:
x = float(val)
y = poly1d_fn(x)
ax.annotate('',xy=(x,0),xycoords=('data','axes fraction'),xytext=(x,y),textcoords='data',arrowprops=dict(arrowstyle='-',ls='--'))
ax.annotate(f'{x:.2f}','axes fraction'))
ax.annotate('',xy=(0,xycoords=('axes fraction','data'),ls='--'))
ax.annotate(f'{y:.2f}','data'))
output_box.set_text(f'Result = {y:.2f}')
plt.draw()
except ValueError:
pass
fig,ax = plt.subplots()
ax.plot(x,'ro',x,poly1d_fn(x),'-b')
ax.errorbar(x,yerr=poly1d_fn(x) - y,fmt='.k')
left,bottom,width,height,pad = 0.15,0.02,0.3,0.10,0.1
fig.subplots_adjust(left=left,bottom=0.25) # Make space for the slider
input_field = fig.add_axes([left,height])
text_box = matplotlib.widgets.TextBox(input_field,'value')
text_box.on_submit(submit)
output_box = fig.text(left+width+pad,bottom+height/2,s='Result = ',va='center')
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。