Error using matplotlib

Asked

Viewed 105 times

-2

Good afternoon, you guys.

I’m starting to work with python and need to generate a graph of a txt, this is divided into 3 columns (where it represents x,y and z) and these are separated by 3 white spaces. When plotting the graph, it results in the following image: https://ibb.co/HD2DBMx

I cannot identify the error, since I already used MATLAB to carry out the drawing of this TXT graph and it came out as expected.

Follow the code below:

import matplotlib.pyplot as plt
import numpy as np
#plt.style.use('classic')


x = []
y = []
z = []

dataset = open('TMM3_7mm.txt', 'r') # esse 'r' é apenas read, podia ser W para write


for line in dataset:
   line = line.strip() # 23,24\n -> 23,24
   X, Y, Z = line.split('   ') #Aqui é dito por qual valor as colunas tão separadas
   x.append(X)
   y.append(Y)
   z.append(Z)


dataset.close() # fecha a base de dados

plt.plot(x,y)


plt.show()

1 answer

0


The problem is that you were passing strings to the function, Plot. When you load the data from txt, it is strings, needs to be converted, to float. Here’s the package documentation matplotlib.

def load_dataset():
    x = []
    y = []
    z = []
    dataset = open('TMM3_7mm.txt', 'r') # esse 'r' é apenas read, podia ser W para write

    for line in dataset:
       line = line.strip() # 23,24\n -> 23,24
       X, Y, Z = line.split('   ') #Aqui é dito por qual valor as colunas tão separadas
       x.append(X)
       y.append(Y)
       z.append(Z)

    x = [float(i) for i in x] # converte todo o array de strings para float
    y = [float(i) for i in y] # converte todo o array de strings para float
    z = [float(i) for i in z] # converte todo o array de strings para float

    dataset.close() # fecha a base de dados

    plt.plot(x,y)

    plt.show()

load_dataset()

With this conversion I obtained the following chart:

inserir a descrição da imagem aqui

Browser other questions tagged

You are not signed in. Login or sign up in order to post.