Python Forum

Full Version: URGENT: How to plot data from text file. Trying to recreate plots from MATLAB
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have the following data saved from a MATLAB code and they have the following form:
Quote:0,0.001,0.002,0.003,0.004,0.005,0.006,0.007,0.008,0.009,0.01,0.011,0.012,0.013,0.014,0.015,0.016,0.017,0.018,..
and I am trying to recreate my plot from MATLAB that looks like:
matlabplot


So I have written the following python code that is not working:
XX, YY =[], []
for line in open('RhoMacCormack_sigpt05_cflpt5.txt','r'):
    values = [float(s) for s in line.split()]
    XX.append(values[0])
    YY.append(values[1])
    plt.plot(XX,YY)
    plt.show()
Gives the error:
ValueError: could not convert string to float: '0,0.001,0.002,0.003,0.004...
Could someone help me get this working?
You should provide separator. By default it's whitespace:

>>> s = '0,0.001,0.002,0.003,0.004,0.005'
>>> s.split()
['0,0.001,0.002,0.003,0.004,0.005']                # no whitespace
>>> s.split(',')
['0', '0.001', '0.002', '0.003', '0.004', '0.005']
(May-08-2021, 08:03 PM)perfringo Wrote: [ -> ]You should provide separator. By default it's whitespace:

>>> s = '0,0.001,0.002,0.003,0.004,0.005'
>>> s.split()
['0,0.001,0.002,0.003,0.004,0.005']                # no whitespace
>>> s.split(',')
['0', '0.001', '0.002', '0.003', '0.004', '0.005']
If I do that I get the plot but it's empty? no data is plotted Huh Huh Huh Huh
python
If you're not getting points on your plot you must not have data in either XX or YY. Your text of the file makes it seem like it's one line. That might get you XX values but I bet YY is empty. Have you looked??? Try printing values after line 3 and make sure you have valid data to plot.
Urgent?? There is lots of info on matplotlib around.

Here is a simple example to get you started.

import numpy
import matplotlib.pyplot as plt
# for locating minor ticks
from matplotlib.ticker import (MultipleLocator, AutoMinorLocator)

def myApp():    
    x = np.arange(0.01, 10.0, 0.01)
    y = x
    z = 2*x    
    fig, ax = plt.subplots(num='My Plot') # name of the output window
    plt.rcParams["figure.figsize"] = [5, 5] # set the size of the output window
    plt.ion() # to make plot non-blocking, i.e. if multiple plots are launched
    ax.plot(x, y, color = 'g', label='y = x')
    ax.plot(x, z, color = 'r', label='y = 2 * x')    
    ax.set_xlim(0, 10)  # increasing time
    ax.set_xlabel('increasing time (s)')
    ax.set_ylabel('voltage (mV)')
    ax.set_title('Crazy stuff ...')
    ax.grid(True)
    ax.legend()
    plt.show()