【问题标题】:python matplotlib -- regenerate graph?python matplotlib——重新生成图形?
【发布时间】:2011-06-13 16:32:18
【问题描述】:

我有一个python 函数,它生成一个包含随机值的列表。

调用此函数后,我调用另一个函数,该函数使用matplotlib 绘制随机值。

我希望能够单击键盘/鼠标上的某个键,并发生以下情况:

(1) 将重新生成一个新的随机值列表

(2) 将绘制来自(1) 的值(替换当前的matplotlib 图表)

意思是,我希望能够通过单击按钮查看新图表。我该如何在python 中执行此操作?

【问题讨论】:

    标签: python matplotlib


    【解决方案1】:

    真的是quite easy to do with matplotlib。基本思想是使用

    plt.connect('button_press_event', onclick)
    

    每当用户按下按钮时调用onclick

    import matplotlib.pyplot as plt
    import numpy as np
    
    class Main(object):
        def clear(self):
            plt.clf()
        def redraw(self):
            self.clear()
            plt.plot(self.data)
            plt.title('100')
            plt.text(50,0.85,'100')
            plt.draw()
        def on_click(self,event):
            self.data=np.random.random(100)    
            self.redraw()        
        def run(self):
            plt.figure()
            plt.connect('button_press_event', self.on_click)
            plt.show() 
    
        def __init__(self):
            self.data=np.random.random(100)    
    
    if __name__=='__main__':           
        m=Main()
        m.run()
        print(m.data)
    

    【讨论】:

    • 谢谢。我会试一下!您能否建议如何在图表的顶部中间部分写文字(例如数字 100)?
    • @user3262424:是的;您可以使用plt.title 在图形的顶部中间部分(绘图轴之外)放置一个字符串。或者,您可以使用plt.text 将字符串放置在绘图轴内的任何位置。我已经修改了redraw 方法来显示两者。
    【解决方案2】:

    从 matplotlib.widgets 导入按钮

    real_points = plt.axes().scatter(x=xpts, y=ypts, alpha=.4, s=size, c='green', label='real data')

    #重置按钮
    #rect = [左、下、宽、高]
    reset_axis = plt.axes([0.4, 0.15, 0.1, 0.04])
    button = Button(ax=reset_axis, label='Reset', color='lightblue' , hovercolor='0.975')

    def 重置(事件):
    real_points.remove()

    button.on_clicked(reset)

    plt.show()

    【讨论】:

      猜你喜欢
      • 2018-04-26
      • 2016-08-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-25
      • 2012-03-18
      相关资源
      最近更新 更多