Gregory Kuhn
Gregory Kuhn

Reputation: 1697

error when calling script which generates a matplotlib plot and saves it

Strange question, I have a script which creates a matplotlib 3d scatter plot and then saves it to a PNG file. The script is: plot_data.py It is shown below:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
#import numpy as np
import argparse
import os
from pylab import *




def get_data(filename):
    data = []
    with open(filename) as F:
        for line in F:
            splitted = line.split(sep=',')
            formatted = (int(x) for x in splitted)
            data.append(formatted)
    return list(map(list, zip(*data)))

def create_plot(data, save_file):

    fig = plt.figure()
    ax = fig.gca(projection='3d')        
    cset = ax.scatter(xs=data[0], ys=data[1], zs=data[2])        
    ax.set_xlabel('DAC0')        
    ax.set_ylabel('DAC1')
    ax.set_zlabel('RSSI')
    fig.set_size_inches(18,12)
    savefig(save_file, dpi=200, transparent=True, bbox_inches='tight', pad_inches=0)


if __name__ == '__main__':


    parser = argparse.ArgumentParser( description = "Visualize the data")
    parser.add_argument('path', help="The path to the data file to visualize")
    parser.add_argument('result_image', help="The path to where the resultant png image should be saved")
    p = parser.parse_args()
    data = get_data(p.path)
    create_plot(data, p.result_image)

The script works just find when I call it from the command line. Like this: python plot_data.py test_data.dat test_data.png

Now, when I try and call it from another script, I run into issues. I made an example script called test_plot.py which tests the plot_data function. BTW, The commented code in test_plot.py was simply used to generate some test data.

test_plot.py is below:

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
import argparse
import os
from pylab import *

from itertools import product



from plot_data import create_plot
from random import randint



if __name__ == '__main__':


    #grid = product(range(5), range(5))
    #xs, ys = list(map(list, zip(*grid)))
    #zs = [randint(0,10) for i in range(len(xs))]
    #my_gen = ('{},{},{}\n'.format(x,y,z) for x,y,z in zip(xs,ys,zs))
    #with open('test_data.dat', 'w') as F:
    #    for x,y,z in zip(xs, ys, zs):
    #        F.writelines(my_gen)

    input_file = r"test_data.dat"
    output_file = r"test_data.png"

    create_plot(input_file, output_file)

When I run this script I get the following output:

c:\projects\a>python test_plot.py
Traceback (most recent call last):
  File "test_plot.py", line 31, in <module>
    create_plot(input_file, output_file)
  File "c:\projects\a\plot_data.py", line 29, in create_
plot
    cset = ax.scatter(xs=data[0], ys=data[1], zs=data[2])
  File "C:\Users\gkuhn\AppData\Local\Continuum\Anaconda3\lib\site-packages\mpl_toolkits\mp
lot3d\axes3d.py", line 2240, in scatter
    patches = Axes.scatter(self, xs, ys, s=s, c=c, *args, **kwargs)
  File "C:\Users\gkuhn\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axes
\_axes.py", line 3660, in scatter
    self.add_collection(collection)
  File "C:\Users\gkuhn\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\axes
\_base.py", line 1459, in add_collection
    self.update_datalim(collection.get_datalim(self.transData))
  File "C:\Users\gkuhn\AppData\Local\Continuum\Anaconda3\lib\site-packages\matplotlib\coll
ections.py", line 189, in get_datalim
    offsets = np.asanyarray(offsets, np.float_)
  File "C:\Users\gkuhn\AppData\Local\Continuum\Anaconda3\lib\site-packages\numpy\core\nume
ric.py", line 514, in asanyarray
    return array(a, dtype, copy=False, order=order, subok=True)
ValueError: could not convert string to float: 't'

c:\projects\a>

If it helps, I am using the anaconda distribution of Python3 64bit on Windows. I presume the problem is some form of namespacing thing?

Upvotes: 0

Views: 202

Answers (1)

Bruce
Bruce

Reputation: 7132

create_plot takes a data set as first parameter, not a file name.

You should fix your test script like this:

from plot_data import create_plot, get_data
(...)
create_plot(get_data(input_file), output_file)

or modify your create_plot to take a file name as first parameter.

Due to python being dynamically typed, it's hard to detect such issues (you could assert on object types in create_plot or write documentation to help you remember that first parameter is a dataset)

Upvotes: 1

Related Questions