2

我正在尝试遵循 youtube 上的教程,现在在教程中他们使用 matplotlib.pyplot 绘制了一些标准文本文件,我可以很容易地做到这一点,但是我现在正尝试使用我拥有的一些 csv 来执行相同的操作真实数据.

我使用的代码是 import matplotlib.pyplot as plt import csv #import numpy as np

with open(r"Example RFI regression axis\Delta RFI.csv") as x, open(r"Example RFI regression axis\strikerate.csv") as y:
    readx = csv.reader(x)
    ready = csv.reader(y)

    plt.plot(readx,ready)

    plt.title ('Test graph')
    plt.xlabel('x axis')
    plt.ylabel('y axis')

    plt.show()

我收到的回溯很长

Traceback (most recent call last):
  File "C:\V4 code snippets\matplotlib_test.py", line 11, in <module>
    plt.plot(readx,ready)
  File "C:\Python27\lib\site-packages\matplotlib\pyplot.py", line 2832, in plot
    ret = ax.plot(*args, **kwargs)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 3997, in plot
    self.add_line(line)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 1507, in add_line
    self._update_line_limits(line)
  File "C:\Python27\lib\site-packages\matplotlib\axes.py", line 1516, in _update_line_limits
    path = line.get_path()
  File "C:\Python27\lib\site-packages\matplotlib\lines.py", line 677, in get_path
    self.recache()
  File "C:\Python27\lib\site-packages\matplotlib\lines.py", line 401, in recache
    x = np.asarray(xconv, np.float_)
  File "C:\Python27\lib\site-packages\numpy\core\numeric.py", line 320, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: float() argument must be a string or a number

请告知我需要做什么,我意识到这对于大多数经验丰富的编码人员来说可能很容易。亲切的问候

4

1 回答 1

9

csv.reader()返回字符串(从技术上讲,.next()阅读器对象的方法返回字符串列表)。如果不将它们转换为floator int,您将无法使用plt.plot()它们。

为了省去转换的麻烦,我建议使用genfromtxt()from numpy。(http://docs.scipy.org/doc/numpy/reference/generated/numpy.genfromtxt.html

比如有两个文件:data1.csv:

data1
2
3
4
3
6
6
4

和data2.csv:

data2
92
73
64
53
16
26
74

他们都有一行标题。我们能做的:

import numpy as np
data1=np.genfromtxt('data1.csv', skip_header=1) #suppose it is in the current working directory
data2=np.genfromtxt('data2.csv', skip_header=1)
plt.plot(data1, data2,'o-')

结果:

在此处输入图像描述

于 2013-10-03T23:08:42.833 回答