导入txt文件matplotlib后显示图形

2024-10-01 13:37:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在编写一个简单的程序,在导入一个文本文件后输出一个基本图形。我得到以下错误:

Traceback (most recent call last):
  File "C:\Users\Chris1\Desktop\attempt2\ex1.py", line 13, in <module>
    x.append(int(xAndY[0]))
ValueError: invalid literal for int() with base 10: '270.286'

我的python代码如下所示:

^{pr2}$

我的文本文件片段如下所示:

270.286,4.353,16968.982,1903.115
38.934,68.608,16909.727,1930.394    
190.989,1.148,16785.367,1969.925         

这个问题看起来很小,但似乎自己解决不了 谢谢


Tags: 程序图形most错误callusersfileint
2条回答

解决方案

如果要将浮点值转换为整数,只需更改

x.append(int(xAndY[0]))
y.append(int(xAndY[1]))

^{pr2}$

enter image description here

你出错的原因

出现错误是因为内置函数int不接受浮点的字符串表示作为其参数。从documentation

int(x=0)
int(x, base=10)
...
If x is not a number or if base is given, then x must be a string or Unicode object representing an integer literal in radix base. Optionally, the literal can be preceded by + or - (with no space in between) and surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with a to z (or A to Z) having values 10 to 35.

在您的例子中(x不是数字,而是浮点的字符串表示),这意味着函数不知道如何转换值。这是因为使用base=10,参数只能包含数字[0-9],即不能包含.(点),这意味着字符串不能是浮点的表示。在


更好的解决方案

我建议您研究一下^{},因为这样更容易使用:

x, y = np.loadtxt('temp.txt',     # Load values from the file 'temp.txt'
                  dtype=int,      # Convert values to integers
                  delimiter=',',  # Comma separated values
                  unpack=True,    # Unpack to several variables
                  usecols=(0,1))  # Use only columns 0 and 1

在更正后,它将生成与代码中相同的xy列表。在

通过这个修改,您的代码可以被缩减为

import matplotlib.pyplot as plt
import numpy as np

x, y = np.loadtxt('temp.txt', dtype=int, delimiter=',',
                  unpack=True, usecols=(0,1))

plt.plot(x, y)

plt.title('example 1')
plt.xlabel('D')
plt.ylabel('Frequency')

plt.show()

很简单,只需将int转换替换为float

for plotPair in sepFile:
    xAndY = plotPair.split(',')
    x.append(float(xAndY[0]))
    y.append(float(xAndY[1]))

这将修复错误。在

相关问题 更多 >