I am trying to create a graph and be able to edit it. When I call the graphExample, I receive the error message. Can anyone please advise? Thanks.
我正在尝试创建一个图形,并能够编辑它。当我调用graphExample时,我接收到错误消息。谁能请通知?谢谢。
import matplotlib.pyplot as plt
def graphExample():
x = []
y = []
readFile = open('C:\Users\user1\Desktop\Sentdex\tutorial_2_notepad.txt', 'r')
sepFile = readFile.read().split('\n') #tells cmd that '\n\' is the end of the line and "splits" it from the next ordered pair
readFile.close()
fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')
for plotPair in sepFile:
xAndy = plotPair.split(',') #tells the program that x and y are separated by the comma in the txt file
x.append(int(xAndy[0]))
y.append(int(xAndy[1]))
ax1 = fig.add_subplot(1,1,1, axisbg='grey')
ax1.plot(x, y, 'c', linewidth=3.3)
ax1.set_title("Brian Changes Color of Graph")
ax1.set_xlabel("X Label Dude")
ax1.set_ylabel("Y Label Dude")
plt.show()
graphExample()
2 个解决方案
#1
1
You need to ensure that xAndy[0]
and xAndy[1]
are valid numbers. Right now one of them is an empty string, which is not a valid number, which makes int()
fail.
您需要确保xAndy[0]和xAndy[1]是有效的数字。现在,其中一个是空字符串,它不是一个有效的数字,它使int()失败。
#2
0
Probably something like this is going on:
大概是这样的:
>>> !cat test.dat
1,2
3,4
>>> open("test.dat").read().split("\n")
['1,2', '3,4', '']
and that last empty string is causing the trouble. Instead of doing any of this, though, you could simply use np.loadtxt
:
最后一个空字符串引起了麻烦。但是,您可以简单地使用np.loadtxt:
>>> np.loadtxt("test.dat", delimiter=",", dtype=int)
array([[1, 2],
[3, 4]])
and unpack to get the columns:
然后打开包以获取列:
>>> x,y = np.loadtxt("test.dat", delimiter=",", dtype=int, unpack=True)
>>> x
array([1, 3])
>>> y
array([2, 4])
#1
1
You need to ensure that xAndy[0]
and xAndy[1]
are valid numbers. Right now one of them is an empty string, which is not a valid number, which makes int()
fail.
您需要确保xAndy[0]和xAndy[1]是有效的数字。现在,其中一个是空字符串,它不是一个有效的数字,它使int()失败。
#2
0
Probably something like this is going on:
大概是这样的:
>>> !cat test.dat
1,2
3,4
>>> open("test.dat").read().split("\n")
['1,2', '3,4', '']
and that last empty string is causing the trouble. Instead of doing any of this, though, you could simply use np.loadtxt
:
最后一个空字符串引起了麻烦。但是,您可以简单地使用np.loadtxt:
>>> np.loadtxt("test.dat", delimiter=",", dtype=int)
array([[1, 2],
[3, 4]])
and unpack to get the columns:
然后打开包以获取列:
>>> x,y = np.loadtxt("test.dat", delimiter=",", dtype=int, unpack=True)
>>> x
array([1, 3])
>>> y
array([2, 4])