0

My dataframe is originally a text file, where the columns are separated by a tab.

I first changed these tabs to spaces by hand (sep=" "), loaded and plotted the data, my plot looked the way it should. Since I have multiple files to plot, its not really handy to change the separator of each file. That's why I changed the seper<tor to sep="\s+". Suddenly the x-axis of my new plot takes every single position value and overlaps them.

Anyone knows why this is happening and how to prevent it?

My first code looked like:

import pandas as pd
import numpy as np
from functools import reduce

data1500 = pd.read_csv('V026-15.000-0.1.txt', sep = " ", index_col='Position')
plt.plot(data_merged1.ts1500, label="ts 15.00")

and the second:

import pandas as pd
import numpy as np
from functools import reduce
from matplotlib import pyplot as plt

data1500 = pd.read_csv('V025-15.000-0.5.txt', sep = "\s+", index_col='Position')
plt.plot(data_merged2.ts1500, label="ts 15.00")
r-beginners
  • 31,170
  • 3
  • 14
  • 32
  • where do `data_merged1` and `data_merged2` come from? – lpounng Apr 21 '22 at 02:07
  • I merge various txt files on the index position in one table together. Probably it's an unnecessary step, but the plot should combine the data of multiple txt files. – Veronika Apr 21 '22 at 10:40

1 Answers1

0

you could do this to import a tab-delimited file:

import re
with open('V026-15.000-0.1.txt.txt') as f:
    data = [re.split('\t',x) for x in f.read().split('\n')]

or do this:

import csv
with open('data.txt', newline = '') as mytext:                                                                                          
   data = csv.reader(mytext, delimiter='\t') 

then to plot your data you should do as follow:

Read each line in the file using for loop.

Append required columns into a list.

After reading the whole file, plot the required data

something like this:

for row in data:
     x.append(row[0])
     y.append(row[1])
plt.plot(x, y)
maryam_k
  • 126
  • 1
  • 7