user3133136
user3133136

Reputation: 37

ValueError: invalid literal for int() with base 10: '' Python / Matplotlib

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.

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()

Upvotes: 0

Views: 2139

Answers (2)

ThiefMaster
ThiefMaster

Reputation: 318558

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.

Upvotes: 1

DSM
DSM

Reputation: 353309

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("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])

Upvotes: 0

Related Questions