I am trying to create a function that plots a chart from a CSV
file that contains labels:
LVL,Highscore
2,6013
2,5934
1,132
3,9560
4,13406
This is the code snippet I tried:
from matplotlib import style
import numpy as np
import csv
def plot():
style.use('ggplot')
x, y = np.loadtxt(
'highscore.csv',
unpack=True,
skiprows=1,
usecols=1,
delimiter=','
)
plot()
And this is the traceback error I'm getting:
Traceback (most recent call last):
File "C:/Users/User/PycharmProjects/FinalYearProject/anothertest.py", line 28, in <module>
plot()
File "C:/Users/User/PycharmProjects/FinalYearProject/anothertest.py", line 18, in plot
x, y = np.loadtxt('highscore.csv', unpack=True,
File "C:\Users\User\PycharmProjects\FinalYearProject\venv\lib\site-packages\numpy\lib\npyio.py", line 1148, in loadtxt
for x in read_data(_loadtxt_chunksize):
File "C:\Users\User\PycharmProjects\FinalYearProject\venv\lib\site-packages\numpy\lib\npyio.py", line 992, in read_data
vals = [vals[j] for j in usecols]
File "C:\Users\User\PycharmProjects\FinalYearProject\venv\lib\site-packages\numpy\lib\npyio.py", line 992, in <listcomp>
vals = [vals[j] for j in usecols]
IndexError: list index out of range
I attempted to resolve it by using the parameter usecols=1
and skiprows=1
, but it still doesn't seem to work.
CodePudding user response:
Not sure if I completely understand your question, but I don't think you need usecols.
>>> import numpy as np
>>> x, y = np.loadtxt('highscore.csv', unpack=True, skiprows=1, delimiter=',')
>>> print(x)
[2., 2., 1., 3., 4.]
>>> print(y)
[ 6013., 5934., 132., 9560., 13406.]
You can then proceed to plot the data. I am not sure which plot you expect, but a scatter plot seems most suitable here
>>> import matplotlib.pyplot as plt
>>> from matplotlib import style
>>> plt.style.use('ggplot')
>>> plt.scatter(x, y)
>>> plt.show()
Which will make this plot:
Does this answer your question?