使用Python从MATLAB .fig文件中获取数据?

Dan*_*Dan 9 python matlab

有谁知道使用Python从MATLAB图文件中提取数据的任何方法?我知道这些是二进制文件,但Python Cookbook for .mat文件http://www.scipy.org/Cookbook/Reading_mat_files中的方法似乎不适用于.fig文件...

在此先感谢任何帮助,Dan

Ram*_*nka 10

.fig文件是.mat文件(包含结构),请参阅 http://undocumentedmatlab.com/blog/fig-files-format/

作为您给出的引用状态,结构仅支持v7.1:http: //www.scipy.org/Cookbook/Reading_mat_files

所以,在MATLAB中我使用-v7保存:

plot([1 2],[3 4])
hgsave(gcf,'c','-v7');
Run Code Online (Sandbox Code Playgroud)

然后在Python 2.6.4中我使用:

>>> from scipy.io import loadmat
>>> x = loadmat('c.fig')
>>> x
{'hgS_070000': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1500e70>]], dtype=object), '__version__': '1.0', '__header__': 'MATLAB 5.0 MAT-file, Platform: MACI64, Created on: Fri Nov 18 12:02:31 2011', '__globals__': []}
>>> x['hgS_070000'][0,0].__dict__
{'handle': array([[1]], dtype=uint8), 'children': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1516030>]], dtype=object), '_fieldnames': ['type', 'handle', 'properties', 'children', 'special'], 'type': array([u'figure'], dtype='<U6'), 'properties': array([[<scipy.io.matlab.mio5.mat_struct object at 0x1500fb0>]], dtype=object), 'special': array([], shape=(1, 0), dtype=float64)}
Run Code Online (Sandbox Code Playgroud)

我曾经在那里.__dict__看到如何遍历结构.例如XData,YData我可以使用:

>>> x['hgS_070000'][0,0].children[0,0].children[0,0].properties[0,0].XData
array([[1, 2]], dtype=uint8)
>>> x['hgS_070000'][0,0].children[0,0].children[0,0].properties[0,0].YData
array([[3, 4]], dtype=uint8)
Run Code Online (Sandbox Code Playgroud)

显示我plot([1 2],[3 4])在MATLAB中使用过(孩子是轴,孙子是lineseries).


Sas*_*cha 8

我发现Alex的答案非常吸引人,但我扩展了他的代码.首先,我在序言中加入了数字,ylabel等的来源.第二,我加入了传奇!我对Python很陌生,所以对任何改进建议都非常欢迎.

def plotFig(filename,fignr=1):
   from scipy.io import loadmat
   from numpy import size
   from matplotlib.pyplot import plot,figure,hold,xlabel,ylabel,show,clf,xlim,legend
   d = loadmat(filename,squeeze_me=True, struct_as_record=False)
   ax1 = d['hgS_070000'].children
   if size(ax1) > 1:
       legs= ax1[1]
       ax1 = ax1[0]
   else:
        legs=0
   figure(fignr)
   clf()
   hold(True)
   counter = 0    
   for line in ax1.children:
       if line.type == 'graph2d.lineseries':
           if hasattr(line.properties,'Marker'):
               mark = "%s" % line.properties.Marker
               mark = mark[0]
           else:
               mark = '.'
           if hasattr(line.properties,'LineStyle'):
               linestyle = "%s" % line.properties.LineStyle
           else:
               linestyle = '-'
           if hasattr(line.properties,'Color'):
               r,g,b =  line.properties.Color
           else:
               r = 0
               g = 0
               b = 1
           if hasattr(line.properties,'MarkerSize'):
               marker_size = line.properties.MarkerSize
           else:
               marker_size = 1                
           x = line.properties.XData
           y = line.properties.YData
           plot(x,y,marker=mark,linestyle=linestyle,\
           color(r,g,b),markersize=marker_size)
       elif line.type == 'text':
           if counter < 1:
               xlabel("%s" % line.properties.String,fontsize =16)
               counter += 1
           elif counter < 2:
               ylabel("%s" % line.properties.String,fontsize = 16)
               counter += 1        
   xlim(ax1.properties.XLim)
   if legs:        
       leg_entries = tuple(legs.properties.String)
       py_locs = ['upper center','lower center','right','left','upper right','upper left','lower right','lower left','best']
       MAT_locs=['North','South','East','West','NorthEast', 'NorthWest', 'SouthEast', 'SouthWest','Best']
       Mat2py = dict(zip(MAT_locs,py_locs))
       location = legs.properties.Location
       legend(leg_entries,loc=Mat2py[location])
    hold(False)
    show()
Run Code Online (Sandbox Code Playgroud)


joh*_*135 7

这是我在Sascha的帖子中的更新.现在它可以:

  • 显示旋转,tex标签
  • 显示xticks和yticks
  • 更好地处理标记
  • 网格开/关
  • 更好的轴和图例枚举处理
  • 保持数字大小

代码如下:

from scipy.io import loadmat
import numpy as np
import matplotlib.pyplot as plt

def plotFig(filename,fignr=1):
   d = loadmat(filename,squeeze_me=True, struct_as_record=False)
   matfig = d['hgS_070000']
   childs = matfig.children
   ax1 = [c for c in childs if c.type == 'axes']
   if(len(ax1) > 0):
       ax1 = ax1[0]
   legs = [c for c in childs if c.type == 'scribe.legend']
   if(len(legs) > 0):
       legs = legs[0]
   else:
       legs=0
   pos = matfig.properties.Position
   size = np.array([pos[2]-pos[0],pos[3]-pos[1]])/96
   plt.figure(fignr,figsize=size)
   plt.clf()
   plt.hold(True)
   counter = 0    
   for line in ax1.children:
       if line.type == 'graph2d.lineseries':
           if hasattr(line.properties,'Marker'):
               mark = "%s" % line.properties.Marker
               if(mark != "none"):
                   mark = mark[0]
           else:
               mark = '.'
           if hasattr(line.properties,'LineStyle'):
               linestyle = "%s" % line.properties.LineStyle
           else:
               linestyle = '-'
           if hasattr(line.properties,'Color'):
               r,g,b =  line.properties.Color
           else:
               r = 0
               g = 0
               b = 1
           if hasattr(line.properties,'MarkerSize'):
               marker_size = line.properties.MarkerSize
           else:
               marker_size = -1                
           x = line.properties.XData
           y = line.properties.YData
           if(mark == "none"):
               plt.plot(x,y,linestyle=linestyle,color=[r,g,b])
           elif(marker_size==-1):
               plt.plot(x,y,marker=mark,linestyle=linestyle,color=[r,g,b])
           else:
               plt.plot(x,y,marker=mark,linestyle=linestyle,color=[r,g,b],ms=marker_size)
       elif line.type == 'text':
           if counter == 0:
               plt.xlabel("$%s$" % line.properties.String,fontsize =16)
           elif counter == 1:
               plt.ylabel("$%s$" % line.properties.String,fontsize = 16)
           elif counter == 3:
               plt.title("$%s$" % line.properties.String,fontsize = 16)
           counter += 1        
   plt.grid(ax1.properties.XGrid)

   if(hasattr(ax1.properties,'XTick')):
       if(hasattr(ax1.properties,'XTickLabelRotation')):
           plt.xticks(ax1.properties.XTick,ax1.properties.XTickLabel,rotation=ax1.properties.XTickLabelRotation)
       else:
           plt.xticks(ax1.properties.XTick,ax1.properties.XTickLabel)
   if(hasattr(ax1.properties,'YTick')):
       if(hasattr(ax1.properties,'YTickLabelRotation')):
           plt.yticks(ax1.properties.YTick,ax1.properties.YTickLabel,rotation=ax1.properties.YTickLabelRotation)
       else:
           plt.yticks(ax1.properties.YTick,ax1.properties.YTickLabel)
   plt.xlim(ax1.properties.XLim)
   plt.ylim(ax1.properties.YLim)
   if legs:        
       leg_entries = tuple(['$' + l + '$' for l in legs.properties.String])
       py_locs = ['upper center','lower center','right','left','upper right','upper left','lower right','lower left','best','best']
       MAT_locs=['North','South','East','West','NorthEast', 'NorthWest', 'SouthEast', 'SouthWest','Best','none']
       Mat2py = dict(zip(MAT_locs,py_locs))
       location = legs.properties.Location
       plt.legend(leg_entries,loc=Mat2py[location])
   plt.hold(False)
   plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 这个脚本很好用 - 我唯一需要改变的是检查 XGrid 属性是否存在: if hasattr(ax1.properties, 'XGrid'): plt.grid(ax1.properties.XGrid) (3认同)
  • @MattWilliams 是的,对于 matplotlib 3,必须删除“plt.hold”调用。另外,就我而言,我必须将“MAT_locs”条目更改为小写。 (2认同)