简体   繁体   English

matplotlib.pyplot.plot,ValueError:无法将字符串转换为float:f

[英]matplotlib.pyplot.plot, ValueError: could not convert string to float: f

I'm trying to use python to make plots. 我正在尝试使用python进行绘图。 Below is the simplified version of my code that cause error. 下面是导致错误的我的代码的简化版本。

import numpy as np
import matplotlib   
import matplotlib.pyplot as plt
matplotlib.use("AGG")

distance = np.array('f')
depth = np.array('f')# make sure these two arrays store float type value

with open('Line671.txt','r') as datafile:
  for line in datafile:
    word_count = 0
    for word in line.split():
        word = float(word)#convert string type to float
        if word_count == 0:
            distance = np.append(distance, word)
        elif word_count == 1:
            depth = np.append(depth, word)
        else:
          print 'Error'
        word_count += 1

datafile.closed


print depth
print distance #outputs looks correct 
# original data is like this: -5.3458000e+00
# output of the array is :['f' '-5.3458' '-5.3463' ..., '-5.4902' '-5.4912' '-5.4926']

plt.plot(depth, distance)# here comes the problem  

The error message says that in line for plt.plot(depth, distance): ValueError: could not convert string to float: f 错误消息说,在行中包含plt.plot(depth,distance):ValueError:无法将字符串转换为float:f
I don't understand this because it seems I converted all string values into float type. 我不明白这一点,因为似乎我已将所有字符串值都转换为浮点类型。 I tried to search this problem on stackoverflow but they all seem to solve the problem once they cast all string values into float or int. 我试图在stackoverflow上搜索此问题,但是一旦将所有字符串值都转换为float或int,它们似乎都可以解决问题。 Can anyone give any suggestion on this problem? 有人可以对此问题提出任何建议吗? I would be really appreciate for any help. 如有任何帮助,我将不胜感激。

You confused the value with the type. 您将值与类型混淆了。 If you're trying to declare the type, you need to use "dtype=". 如果要声明类型,则需要使用“ dtype =“。 What you actually did was to stick a single character into the array. 您实际上所做的是将单个字符粘贴到数组中。

To answer a later question, your line 要回答以后的问题,您的电话

word = float(word)

likely worked just fine. 可能工作得很好。 However, we can't tell because you didn't do anything with the resulting value. 但是,我们不能说,因为您没有对结果值做任何事情。 Are you expecting this to alter the original inside the variable "line"? 您是否希望这会更改变量“行”内的原始行? Common variables don't work that way. 普通变量不能那样工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM