【问题标题】:Error messages in MatplotlibMatplotlib 中的错误消息
【发布时间】:2015-12-07 20:26:17
【问题描述】:

我正在尝试在 matplotlib 中绘制此数据,但收到以下错误消息:

raise TypeError('Unrecognized argument type %s to close'%type(arg))
TypeError: Unrecognized argument type <type 'list'> to close

我发送给它的数据不是一个字符串,它是一个浮点数,你可以从下面的代码中看到:

import os
import csv
import glob as g
import pprint as p
import matplotlib.pyplot as plt

os.chdir('F:\\')

def graphWriter():
    for file in g.glob('*.TXT'):
        for col in csv.DictReader(open(file,'rU')):
            set_ = int(col[' Set'])
            iriR = float(col[' IRI R e'])
            iriL = float(col['IRI LWP '])
            rutL = float(col[' RUT L e'])
            rutR = float(col[' RUT R e'])
            start = float(col['Start-Mi'])
            end = float(col['  End-Mi'])

    fig = plt.plot(iriR,iriL)
    plt.show()
    plt.close(fig)

graphWriter()

虽然窗口即将显示数据图表且单位正确,但图表中也没有线条,这可能是由于明显的数据问题所致。所以问题是导致错误消息的原因,以及导致图表中没有数据线的原因。但这两者很可能是相关的。这是一些输入数据,尽管我只是想将两个数据集绘制到右侧,即 iriR 和 iriL,如上所示:

(194.449, 194.549, 90.0, 77.9)
(194.549, 194.649, 84.6, 81.5)
(194.649, 194.749, 88.4, 84.1)
(194.749, 194.849, 69.5, 82.9)
(194.849, 194.949, 76.2, 71.0)

【问题讨论】:

  • 函数graphWriter 中的for 循环似乎有一个不好的缩进。对吗?
  • 是的,虽然它现在已修复,但它是正确的。该错误只是来自复制粘贴,不在 IDE 中
  • 在哪一行中断?
  • 你能举个输入文件的例子吗?
  • 很难说它在哪里坏了。当我只是对数据进行输出时,它工作正常。对话框显示,没有一行。然后在我关闭图形对话框后,python shell 中会显示错误消息。

标签: python file csv matplotlib


【解决方案1】:

问题在于函数plt.plot returns a list of lines(已添加到绘图中),而不是Figure 对象--- 而plt.close 只接受Figure 对象。有很多方法可以解决这个问题,

首先,获取图形对象(“get current figure”):

fig = plt.gcf()
plt.close(fig)

其次,不带参数调用 close:plt.close() --- 这将自动关闭活动图形。

第三,关闭所有数字:plt.close('all')

All of these usages are covered in the matplotlib.pyplot.close documentation.

编辑:

下一个问题是您没有将值数组存储到变量中,而只是存储了一个浮点值。您可以初始化一个列表,并将新元素存储到其中。

os.chdir('F:\\')
iriR = []   # Initialize a list

def graphWriter():
    for file in g.glob('*.TXT'):
        for col in csv.DictReader(open(file,'rU')):
            set_ = int(col[' Set'])
            iriR.append(float(col[' IRI R e']))   # Append new entry

对要绘制的其他变量执行相同的操作。

【讨论】:

  • 那我还应该有 fig = plt.plot(iriR,iriL) 吗?
  • @hollow_Victory no... 那么您将重写该变量。
  • 这解决了错误问题,但图表仍然是空白
  • @hollow_Victory 那是因为你的变量 iriRiriL 只保存你打开的最后一个文件的最后一列中的单个值。您始终可以使用 print 语句来查看变量,例如print(iriR)。我也编辑了我的答案来解决这个问题。
  • 是的,我希望我不必为每个变量都列出一个列表。我知道这可能会奏效,而且做得很好。
【解决方案2】:

也许这会奏效。

import pandas as pd
import matplotlib.pyplot as plt
import glob as g

def graphWriter():
    data = {}
    for file in g.glob('*.TXT'):
        data[file] = pd.read_csv(file)
        # Removes ')' and turn it into float
        data[file][3] = data[file][3].apply(lambda x:x[:-1]).astype(float)

    fig, ax  = plt.subplots()

    for d in data.itervalues():
        ax.plot(d[:,2], d[:,3])

    plt.show()
    plt.close(fig)

graphWriter()

该函数将获取以.TXT 结尾的文件列表,然后将它们加载到字典中,其中键是文件的名称。稍后将绘制它们。

更新

由于 OP 发帖说pandas 不可用,所以可以使用numpy

import numpy as np
import matplotlib.pyplot as plt
import glob as g

def graphWriter():
    data = {}
    for file in g.glob('*.TXT'):
        data[file] =  np.fromregex(file, '\d*\.\d*', 
                                   dtype=[('1', float), ('2', float),
                                          ('3', float), ('4', float)])

    fig, ax  = plt.subplots()

    for d in data.itervalues():
        ax.plot(d['3'], d['4'])

    plt.show()
    plt.close(fig)

graphWriter()

【讨论】:

  • 非常好,但它产生了以下错误:ValueError: could not convert string to float: Line,
  • 但我刚刚意识到这并没有正确地遍历数据集。我认为它只是停在第一排。这就是我现在指的代码。
  • numpy.loadtxt 可能因为开头和结尾的括号而不起作用。
  • @hollow_Victory 我更新了它。可以试试吗?
  • 我无法再导入 Pandas。我试过了,我不知道为什么我输了。我在工作,它发生在我们更新系统时
猜你喜欢
  • 2020-07-25
  • 2023-04-09
  • 2012-11-29
  • 2012-03-28
  • 2012-05-31
  • 2011-07-11
  • 1970-01-01
  • 2015-09-18
  • 1970-01-01
相关资源
最近更新 更多