2011-01-30 70 views
8

我已经在文本文件中收集了一些数据,并且想要创建一个boxplot。 但是这个数据文件包含例如可变长度的行。matplotlib中带有可变长度数据的Boxplot

1.2,2.3,3.0,4.5
1.1,2.2,2.9

为相等的长度我可以做
PW = numpy.loadtxt( “./ learning.dat”)
matplotlib.boxplot (PW.T);

如何处理变长数据行?

+0

应该如何解释数据?是否应该将所有值连接在单个一维数组中? – 2011-01-30 12:16:47

+0

不,我想有数据文件列的boxlot。所以在等长的情况下我会做一个m次n数组,然后boxplot转置,对吧? – Kabbo 2011-01-30 12:25:00

回答

16

只需使用数组或列表的列表。 boxplot将采取任何顺序(嗯,任何有__len__,无论如何,它不会与发电机等工作)。

例如为:

import matplotlib.pyplot as plt 
x = [[1.2, 2.3, 3.0, 4.5], 
    [1.1, 2.2, 2.9]] 
plt.boxplot(x) 
plt.show() 

enter image description here

如果你问如何在数据读取,有很多方法可以做你想做的。举个简单的例子:

import matplotlib.pyplot as plt 
import numpy as np 

def arrays_from_file(filename): 
    """Builds a list of variable length arrays from a comma-delimited text file""" 
    output = [] 
    with open(filename, 'r') as infile: 
     for line in infile: 
      line = np.array(line.strip().split(','), dtype=np.float) 
      output.append(line) 
    return output 

plt.boxplot(arrays_from_file('test.txt')) 
plt.show() 
2

你也可以在Plot.ly中使用Python API或仅在GUI中执行boxplot。我做了this graph,你可以在浏览器或与Python API这样做:

box1 = {'y': [1.2, 2.3, 3.0, 4.5], 
'type': 'box'} 
box2 = {'y': [1.1, 2.2, 2.9], 
'type': 'box'} 
response = py.plot([box1, box2]) 
url = response['url'] 
filename = response['filename'] 

全面披露:我对Plotly队。

enter image description here