matplotlib实现交换式图形显示

来源:互联网 发布:知呱呱可不可信 编辑:程序博客网 时间:2024/05/21 09:22

一 代码

  1. from random import choice
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. from matplotlib.widgets importRadioButtons,Button
  5. t = np.arange(0.0,2.0,0.01)
  6. s0 = np.sin(2*np.pi*t)
  7. s1 = np.sin(4*np.pi*t)
  8. s2 = np.sin(8*np.pi*t)
  9. fig, ax = plt.subplots()
  10. l,= ax.plot(t, s0, lw=2, color='red')
  11. plt.subplots_adjust(left=0.3)
  12. #定义允许的几种频率,并创建单选钮组件
  13. #其中[0.05, 0.7, 0.15, 0.15]表示组件在窗口上的归一化位置
  14. axcolor ='lightgoldenrodyellow'
  15. rax = plt.axes([0.05,0.7,0.15,0.15], axisbg=axcolor)
  16. radio =RadioButtons(rax,('2 Hz','4 Hz','8 Hz'))
  17. hzdict ={'2 Hz': s0,'4 Hz': s1,'8 Hz': s2}
  18. def hzfunc(label):
  19. ydata = hzdict[label]
  20. l.set_ydata(ydata)
  21. plt.draw()
  22. radio.on_clicked(hzfunc)
  23. #定义允许的几种颜色,并创建单选钮组件
  24. rax = plt.axes([0.05,0.4,0.15,0.15], axisbg=axcolor)
  25. colors =('red','blue','green')
  26. radio2 =RadioButtons(rax, colors)
  27. def colorfunc(label):
  28. l.set_color(label)
  29. plt.draw()
  30. radio2.on_clicked(colorfunc)
  31. #定义允许的几种线型,并创建单选钮组件
  32. rax = plt.axes([0.05,0.1,0.15,0.15], axisbg=axcolor)
  33. styles =('-','--','-.','steps',':')
  34. radio3 =RadioButtons(rax, styles)
  35. def stylefunc(label):
  36. l.set_linestyle(label)
  37. plt.draw()
  38. radio3.on_clicked(stylefunc)
  39. #定义按钮单击事件处理函数,并在窗口上创建按钮
  40. def randomFig(event):
  41. #随机选择一个频率,同时设置单选钮的选中项
  42. hz = choice(tuple(hzdict.keys()))
  43. hzLabels =[label.get_text()for label in radio.labels]
  44. radio.set_active(hzLabels.index(hz))
  45. l.set_ydata(hzdict[hz])
  46. #随机选择一个颜色,同时设置单选钮的选中项
  47. c = choice(colors)
  48. radio2.set_active(colors.index(c))
  49. l.set_color(c)
  50. #随机选择一个线型,同时设置单选钮的选中项
  51. style = choice(styles)
  52. radio3.set_active(styles.index(style))
  53. l.set_linestyle(style)
  54. #根据设置的属性绘制图形
  55. plt.draw()
  56. axRnd = plt.axes([0.5,0.015,0.2,0.045])
  57. buttonRnd =Button(axRnd,'Random Figure')
  58. buttonRnd.on_clicked(randomFig)
  59. #显示图形
  60. plt.show()
二 运行结果

 
  • 大小: 37.9 KB
  • 查看图片附件
原创粉丝点击