Python + GNU Plot:处理缺失值
为了让问题更清楚,我把它单独拿出来,并用一个小的完整代码片段来描述。
我有一堆数据,但有很多地方缺失。我想忽略这些缺失的数据(如果是折线图的话,就像图表中出现了断点)。我把“?”设置为缺失数据的符号。这里是我的代码片段:
import math
import Gnuplot
gp = Gnuplot.Gnuplot(persist=1)
gp("set datafile missing '?'")
x = range(1000)
y = [math.sin(a) + math.cos(a) + math.tan(a) for a in x]
# Force a piece of missing data
y[4] = '?'
data = Gnuplot.Data(x, y, title='Plotting from Python')
gp.plot(data);
gp.hardcopy(filename="pyplot.png",terminal="png")
但是它没有按我想的那样工作:
> python missing_test.py
Traceback (most recent call last):
File "missing_test.py", line 8, in <module>
data = Gnuplot.Data(x, y, title='Plotting from Python')
File "/usr/lib/python2.6/dist-packages/Gnuplot/PlotItems.py", line 560, in Data
data = utils.float_array(data)
File "/usr/lib/python2.6/dist-packages/Gnuplot/utils.py", line 33, in float_array
return numpy.asarray(m, numpy.float32)
File "/usr/lib/python2.6/dist-packages/numpy/core/numeric.py", line 230, in asarray
return array(a, dtype, copy=False, order=order)
ValueError: setting an array element with a sequence.
到底出了什么问题呢?
1 个回答
4
Gnuplot正在调用numpy.asarray
这个命令,把你的Python列表转换成一个numpy数组。可惜的是,这个命令(加上dtype=numpy.float32
)不适合包含字符串的Python列表。
你可以这样复现这个错误:
In [36]: np.asarray(['?',1.0,2.0],np.float32)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
/usr/lib/python2.6/dist-packages/numpy/core/numeric.pyc in asarray(a, dtype, order)
228
229 """
--> 230 return array(a, dtype, copy=False, order=order)
231
232 def asanyarray(a, dtype=None, order=None):
ValueError: setting an array element with a sequence.
此外,Gnuplot的Python模块(版本1.7)的文档提到:
- 数组数据中没有缺失数据点的处理(而gnuplot可以通过'设置缺失'命令来处理)。
我不确定在1.8版本中这个问题是否已经修复。
你对gnuplot有多依赖呢?你试过matplotlib吗?