收藏 分享(赏)

python 应用实例.pdf

上传人:精品资料 文档编号:10018759 上传时间:2019-09-29 格式:PDF 页数:93 大小:1.81MB
下载 相关 举报
python 应用实例.pdf_第1页
第1页 / 共93页
python 应用实例.pdf_第2页
第2页 / 共93页
python 应用实例.pdf_第3页
第3页 / 共93页
python 应用实例.pdf_第4页
第4页 / 共93页
python 应用实例.pdf_第5页
第5页 / 共93页
点击查看更多>>
资源描述

1、matplotlib 绘制动画的示例 matplotlib 从 1.1.0 版本以后就开始支持绘制动画 下面是几个的示例: 第一个例子使用 generator,每隔两秒,就运行函数 data_gen: python view plaincopyprint? 1. # -*- coding: utf-8 -*- 2. 3. import numpy as np 4. import matplotlib.pyplot as plt 5. import matplotlib.animation as animation 6. 7. fig = plt.figure() 8. axes1 = fig.

2、add_subplot(111) 9. line, = axes1.plot(np.random.rand(10) 10. 11. #因为 update的参数是调用函数 data_gen,所以第一个默认参数不能是 framenum 12. def update(data): 13. line.set_ydata(data) 14. return line, 15. # 每次生成 10 个随机数据 16. def data_gen(): 17. while True: 18. yield np.random.rand(10) 19. 20. ani = animation.FuncAnimati

3、on(fig, update, data_gen, interval=2*1000) 21. plt.show() 第二个 例子使用 list( metric),每次从 metric 中取一行数据作为参数送入 update 中: python view plaincopyprint? 1. import numpy as np 2. import matplotlib.pyplot as plt 3. import matplotlib.animation as animation 4. 5. start = 1, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.0

4、7, 0.58, 0 6. 7. metric =0.03, 0.86, 0.65, 0.34, 0.34, 0.02, 0.22, 0.74, 0.66, 0.65, 8. 0.43, 0.18, 0.63, 0.29, 0.03, 0.24, 0.86, 0.07, 0.58, 0.55, 9. 0.66, 0.75, 0.01, 0.94, 0.72, 0.77, 0.20, 0.66, 0.81, 0.52 10. 11. 12. fig = plt.figure() 13. window = fig.add_subplot(111) 14. line, = window.plot(s

5、tart) 15. #如果是参数是 list,则默认每次取 list中的一个元素 ,即 metric0,metric1,. 16. def update(data): 17. line.set_ydata(data) 18. return line, 19. 20. ani = animation.FuncAnimation(fig, update, metric, interval=2*1000) 21. plt.show() 第三个例子: python view plaincopyprint? 1. import numpy as np 2. from matplotlib import

6、pyplot as plt 3. from matplotlib import animation 4. 5. # First set up the figure, the axis, and the plot element we want to animate 6. fig = plt.figure() 7. ax = plt.axes(xlim=(0, 2), ylim=(-2, 2) 8. line, = ax.plot(, , lw=2) 9. 10. # initialization function: plot the background of each frame 11. d

7、ef init(): 12. line.set_data(, ) 13. return line, 14. 15. # animation function. This is called sequentially 16. # note: i is framenumber 17. def animate(i): 18. x = np.linspace(0, 2, 1000) 19. y = np.sin(2 * np.pi * (x - 0.01 * i) 20. line.set_data(x, y) 21. return line, 22. 23. # call the animator.

8、 blit=True means only re-draw the parts that have changed. 24. anim = animation.FuncAnimation(fig, animate, init_func=init, 25. frames=200, interval=20, blit=True) 26. 27. #anim.save(basic_animation.mp4, fps=30, extra_args=-vcodec, libx264) 28. 29. plt.show() 第四个例子 : python view plaincopyprint? 1. #

9、 -*- coding: utf-8 -*- 2. 3. import numpy as np 4. import matplotlib.pyplot as plt 5. import matplotlib.animation as animation 6. 7. # 每次产生一个新的坐标点 8. def data_gen(): 9. t = data_gen.t 10. cnt = 0 11. while cnt = xmax: 34. ax.set_xlim(xmin, 2*xmax) 35. ax.figure.canvas.draw() 36. line.set_data(xdata,

10、 ydata) 37. 38. return line, 39. 40. # 每隔 10秒调用函数 run,run的参数为函数 data_gen, 41. # 表示图形只更新需要绘制的元素 42. ani = animation.FuncAnimation(fig, run, data_gen, blit=True, interval=10,43. repeat=False) 44. plt.show() 再看下面 的例子 : python view plaincopyprint? 1. # -*- coding: utf-8 -*- 2. import numpy as np 3. impo

11、rt matplotlib.pyplot as plt 4. import matplotlib.animation as animation 5. 6. #第一个参数必须为 framenum 7. def update_line(num, data, line): 8. line.set_data(data.,:num) 9. return line, 10. 11. fig1 = plt.figure() 12. 13. data = np.random.rand(2, 15) 14. l, = plt.plot(, , r-) 15. plt.xlim(0, 1) 16. plt.yli

12、m(0, 1) 17. plt.xlabel(x) 18. plt.title(test) 19. 20. #framenum从 1增加大 25后 ,返回再次从 1增加到 25,再返回 . 21. line_ani = animation.FuncAnimation(fig1, update_line, 25,fargs=(data, l),interval=50, blit=True) 22. 23. #等同于 24. #line_ani = animation.FuncAnimation(fig1, update_line, frames=25,fargs=(data, l), 25. #

13、 interval=50, blit=True) 26. 27. #忽略 frames参数 ,framenum 会从 1一直增加下去知道无穷 28. #由于 frame达到 25以后 ,数据不再改变 ,所以你会发现到达 25以后图形不再变化了 29. #line_ani = animation.FuncAnimation(fig1, update_line, fargs=(data, l), 30. # interval=50, blit=True) 31. 32. plt.show() 测试如何将 MatPlotLib 嵌入到 wxPython 中 测试如何将 MatPlotLib 嵌入到

14、wxPython 中 : python view plaincopyprint? 1. # -*- coding: utf-8 -*- 2. # 3. # wxMPL_test.pyw 4. #author: Wu Xuping 5. #Date : 2013-09-15 6. #测试如何将 MatPlotLib嵌入到 wxPython中 7. # 8. import numpy as np 9. import wx 10. import matplotlib 11. 12. # matplotlib采用 WXAgg为后台 ,将 matplotlib嵌入 wxPython中 13. matpl

15、otlib.use(“WXAgg“) 14. from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg as FigureCanvas 15. from matplotlib.figure import Figure 16. from matplotlib.backends.backend_wx import NavigationToolbar2Wx as NavigationToolbar 17. 18. # 19. class MPL_Panel(wx.Panel): 20. #MPL_Panel面板 ,可以继承或者创建

16、实例 21. def _init_(self,parent): 22. wx.Panel._init_(self,parent=parent, id=-1) 23. 24. self.Figure = matplotlib.figure.Figure(figsize=(4,3) 25. self.axes = self.Figure.add_axes(0.1,0.1,0.8,0.8) 26. self.FigureCanvas = FigureCanvas(self,-1,self.Figure) 27. 28. #继承鼠标移动显示鼠标处坐标的事件 29. self.FigureCanvas.

17、mpl_connect(motion_notify_event,self.MPLOnMouseMove) 30. 31. self.NavigationToolbar = NavigationToolbar(self.FigureCanvas) 32. 33. self.StaticText = wx.StaticText(self,-1,label=Show Help String)34. 35. self.SubBoxSizer = wx.BoxSizer(wx.HORIZONTAL) 36. self.SubBoxSizer.Add(self.NavigationToolbar,prop

18、ortion =0, border= 2,flag = wx.ALL | wx.EXPAND) 37. self.SubBoxSizer.Add(self.StaticText,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND) 38. 39. self.TopBoxSizer = wx.BoxSizer(wx.VERTICAL) 40. self.TopBoxSizer.Add(self.SubBoxSizer,proportion =-1, border = 2,flag = wx.ALL | wx.EXPAND) 41. self.

19、TopBoxSizer.Add(self.FigureCanvas,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND) 42. 43. self.SetSizer(self.TopBoxSizer) 44. 45. #显示坐标值 46. def MPLOnMouseMove(self,event): 47. 48. ex=event.xdata#这个数据类型是 numpy.float64 49. ey=event.ydata#这个数据类型是 numpy.float64 50. if ex and ey : 51. #可以将 numpy.

20、float64类型转化为 float 类型 ,否则格式字符串可能会出错 52. self.StaticText.SetLabel(%10.5f,%10.5f % (float(ex),float(ey) 53. #也可以这样 54. #self.StaticText.SetLabel(%s,%s % (ex,ey) 55. 56. # 57. # MPL_Frame添加了 MPL_Panel的 1个实例 58. # 59. class MPL_Frame(wx.Frame): 60. “MPL_Frame可以继承 ,并可修改 ,或者直接使用 “ 61. def _init_(self,titl

21、e=“MPL_Frame Example In wxPython“,size=(800,500): 62. wx.Frame._init_(self,parent=None,title = title,size=size) 63. 64. self.MPL = MPL_Panel(self) 65. self.Figure = self.MPL.Figure 66. self.axes = self.MPL.axes 67. self.FigureCanvas = self.MPL.FigureCanvas 68. 69. self.RightPanel = wx.Panel(self,-1)

22、 70. #测试按钮 1 71. self.Button1 = wx.Button(self.RightPanel,-1,“TestButton“,size=(100,40),pos=(10,10) 72. self.Button1.Bind(wx.EVT_BUTTON,self.Button1Event) 73. #创建 FlexGridSizer 74. self.FlexGridSizer=wx.FlexGridSizer( rows=5, cols=1, vgap=5,hgap=5) 75. self.FlexGridSizer.SetFlexibleDirection(wx.BOTH

23、) 76. #加入 Sizer中 77. self.FlexGridSizer.Add(self.Button1,proportion =0, border = 5,flag = wx.ALL | wx.EXPAND) 78. 79. 80. self.RightPanel.SetSizer(self.FlexGridSizer) 81. 82. self.BoxSizer=wx.BoxSizer(wx.HORIZONTAL) 83. self.BoxSizer.Add(self.MPL,proportion =-10, border = 2,flag = wx.ALL | wx.EXPAND

24、) 84. self.BoxSizer.Add(self.RightPanel,proportion =0, border = 2,flag = wx.ALL | wx.EXPAND) 85. 86. self.SetSizer(self.BoxSizer) 87. #MPL_Frame界面居中显示 88. self.Centre(wx.BOTH) 89. 90. #按钮事件 ,用于测试绘图 91. def Button1Event(self,event): 92. x=np.arange(-10,10,0.25) 93. y=np.cos(x) 94. self.axes.plot(x,y,

25、-b*) 95. self.axes.grid(True) 96. self.FigureCanvas.draw()#一定要实时更新 97. 98. 99. 100. # 101. 102. #主程序测试 103. if _name_ = _main_: 104. app = wx.PySimpleApp() 105. #frame = MPL2_Frame() 106. frame =MPL_Frame() 107. frame.Center() 108. frame.Show() 109. app.MainLoop() 图像如下 : Python中利用 reportlab将目录下所有的文本

26、文件打印成 pdf Python 中利用 reportlab 将目录下所有的文本文件打印成 pdf: python view plaincopyprint? 1. # -*- coding: utf8 -*- 2. # #- 3. 4. import wlab #pip install wlab 5. import reportlab.pdfbase.ttfonts 6. #reportlab.pdfbase.pdfmetrics.registerFont(reportlab.pdfbase.ttfonts.TTFont(song, /usr/share/fonts/cn/msjh.ttf)

27、7. #import reportlab.lib.fonts 8. # 9. from reportlab.pdfgen import canvas 10. from reportlab.lib.units import inch 11. # 12. def file2pdf(FileName): 13. fpi=FileName.find(.) 14. if (fpi0): 15. outputfn=FileName0:fpi+.pdf 16. else: 17. outputfn=FileName+.pdf 18. c = canvas.Canvas(outputfn) 19. #c.se

28、tFont(song,10) 20. textobject = c.beginText() 21. textobject.setTextOrigin(inch,11*inch) 22. file=open(FileName) 23. n=0 24. for line in file: 25. n=n+1 26. if(nSubStrList=F,EMS,txt 18. #Str=F06925EMS91.txt 19. #IsSubString(SubStrList,Str)#return True (or False) 20. 21. flag=True 22. for substr in S

29、ubStrList: 23. if not(substr in Str): 24. flag=False 25. 26. return flag 27. # #- 28. def GetFileList(FindPath,FlagStr=): 29. 30. #获取目录中指定的文件名 31. #FlagStr=F,EMS,txt #要求文件名称中包含这些字符 32. #FileList=GetFileList(FindPath,FlagStr) # 33. 34. import os 35. FileList= 36. FileNames=os.listdir(FindPath) 37. if

30、 (len(FileNames)0): 38. for fn in FileNames: 39. if (len(FlagStr)0): 40. #返回指定类型的文件名 41. if (IsSubString(FlagStr,fn): 42. fullfilename=os.path.join(FindPath,fn) 43. FileList.append(fullfilename) 44. else: 45. #默认直接返回所有文件名 46. fullfilename=os.path.join(FindPath,fn) 47. FileList.append(fullfilename) 4

31、8. 49. #对文件名排序 50. if (len(FileList)0): 51. FileList.sort() 52. 53. return FileList 可以使用 pip 在线安装 wlab python view plaincopyprint? 1. pip install wlab 还是给个图吧: 使用 matplotlib 的示例:调整字体 -设置刻度、坐标、 colormap和 colorbar 等 使用 matplotlib 的示例:调整字体 -设置刻度、坐标、 colormap 和 colorbar 等 python view plaincopyprint? 1. #

32、 -*- coding: utf-8 -*- 2. #* 3. import os 4. import numpy as np 5. import wlab #pip install wlab 6. import matplotlib 7. import matplotlib.cm as cm 8. import matplotlib.pyplot as plt 9. from matplotlib.ticker import MultipleLocator 10. from scipy.interpolate import griddata 11. matplotlib.rcParamsxt

33、ick.direction = out 12. matplotlib.rcParamsytick.direction = out 13. #* 14. FreqPLUS=F06925,F10650,F23800,F18700,F36500,F89000 15. # 16. FindPath=/d3/MWRT/R20130805/ 17. #* 18. fig = plt.figure(figsize=(8,6), dpi=72, facecolor=“white“) 19. axes = plt.subplot(111) 20. axes.cla()#清空坐标轴内的所有内容 21. #指定图形

34、的字体 22. font = family : serif, 23. color : darkred, 24. weight : normal, 25. size : 16, 26. 27. #* 28. # 查找目录总文件名中保护 F06925, EMS和 txt字符的文件 29. for fp in FreqPLUS: 30. FlagStr=fp,EMS,txt 31. FileList=wlab.GetFileList(FindPath,FlagStr) 32. # 33. LST=#地表温度 34. EMS=#地表发射率 35. TBH=#水平极化亮温 36. TBV=#垂直极化亮温

35、 37. # 38. findex=0 39. for fn in FileList: 40. findex=findex+1 41. if (os.path.isfile(fn): 42. print(str(findex)+fn) 43. #fn=/d3/MWRT/R20130805/F06925_EMS60.txt 44. data=wlab.dlmread(fn) 45. EMS=EMS+list(data:,1)#地表发射率 46. LST=LST+list(data:,2)#温度 47. TBH=TBH+list(data:,8)#水平亮温 48. TBV=TBV+list(dat

36、a:,9)#垂直亮温 49. #- 50. #生成格点数据,利用 griddata插值 51. grid_x, grid_y = np.mgrid275:315:1, 0.60:0.95:0.01 52. grid_z = griddata(LST,EMS), TBH, (grid_x, grid_y), method=cubic) 53. #将横纵坐标都映射到( 0, 1)的范围内 54. extent=(0,1,0,1) 55. #指定 colormap 56. cmap = matplotlib.cm.jet 57. #设定每个图的 colormap和 colorbar所表示范围是一样的

37、,即归一化 58. norm = matplotlib.colors.Normalize(vmin=160, vmax=300) 59. #显示图形,此处没有使用contourf #ctf=plt.contourf(grid_x,grid_y,grid_z) 60. gci=plt.imshow(grid_z.T, extent=extent, origin=lower,cmap=cmap, norm=norm) 61. #配置一下坐标刻度等 62. ax=plt.gca() 63. ax.set_xticks(np.linspace(0,1,9) 64. ax.set_xticklabels

38、( (275, 280, 285, 290, 295, 300, 305, 310, 315) 65. ax.set_yticks(np.linspace(0,1,8) 66. ax.set_yticklabels( (0.60, 0.65, 0.70, 0.75, 0.80,0.85,0.90,0.95) 67. #显示 colorbar 68. cbar = plt.colorbar(gci) 69. cbar.set_label($T_B(K)$,fontdict=font) 70. cbar.set_ticks(np.linspace(160,300,8) 71. cbar.set_t

39、icklabels( (160, 180, 200, 220, 240, 260, 280, 300) 72. #设置 label 73. ax.set_ylabel(Land Surface Emissivity,fontdict=font) 74. ax.set_xlabel(Land Surface Temperature(K),fontdict=font) #陆地地表温度 LST 75. #设置 title 76. titleStr=$T_B$ for Freq = +str(float(fp1:-1)*0.01)+GHz 77. plt.title(titleStr) 78. fig

40、name=fp+.png 79. plt.savefig(figname) 80. plt.clf()#清除图形 81. 82. #plt.show() 83. print(ALL - Finished OK) 上面的例子中,每个保存的图,都是用同样的 colormap,并且每个图的颜色映射值都是一样的,也就是说第一个图中如果 200 表示蓝色,那么其他图中的 200 也表示蓝色。 示例的图形如下: python 中使用 ctypes 调用 MinGW 生成的动态链接库( dll) 关于 gcc 编译 dll 的我就不说了,网上举例一大堆,下面以 g+为例。 假设有一个 test.cpp 文件

41、如下: cpp view plaincopyprint? 1. extern “C“ 2. _declspec(dllexport) double add(double x,double y); 3. 4. 5. double add(double x,double y) 6. return x+y; 7. 在 MinGW 中使用 g+编译: plain view plaincopyprint? 1. g+ -shared -Wl,-kill-at,-output-def,test.def -o test.dll test.cpp 在 python 中可以这样调用生成的 dll 文件: pyt

42、hon view plaincopyprint? 1. import ctypes 2. dll = ctypes.cdll.LoadLibrary(test.dll) #加载动态链接库 3. f=dll.add #提取函数 4. f.argtypes=ctypes.c_double,ctypes.c_double #定 义参数类型 5. f.restype=ctypes.c_double #定义函数返回值类型 6. f(2.5,3.5) #计算 显示的结果为 : plain view plaincopyprint? 1. 6.0 注意: 加载的时候要根据你将要调用的函数是符合什么调用约定的。 stdcall 调用约定:两种加载方式 python view plaincopyprint? 1. Objdll = ctypes.windll.LoadLibra

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 企业管理 > 管理学资料

本站链接:文库   一言   我酷   合作


客服QQ:2549714901微博号:道客多多官方知乎号:道客多多

经营许可证编号: 粤ICP备2021046453号世界地图

道客多多©版权所有2020-2025营业执照举报