Home > front end >  *args calling plt.plot() for each optional argument
*args calling plt.plot() for each optional argument

Time:07-16

I'm having some trouble with passing an arbitrary number of arguments to plt.plot(). For each argument I try to pass via *args my function calls plt.plot() two times creating duplicates for each optional argument. The read_n_plot function is meant to read some datafile, spit out the data as lists, and create a plot of said data. If I want to create a plot of an XRD standard for a crystal I want to make it easily distinguishable from whatever experimental data I'm comparing it with.

From what I understand *args is a tuple containing all the arguments passed to my function. But I can't seem to figure out how to pass everything inside *args as is, and not calling plt.plot(arg1) -> plt.plot(arg2) -> etc

Got any hints I could try?

Here is my code:

import matplotlib.pyplot as plt

#def read_n_plot(datafile, color, thickness, style = '-', *args):
def read_n_plot(datafile, *args, **kwargs):
    vinkel = []
    intensitet = []
    with open(datafile, encoding='utf8', errors='ignore') as f:
        if datafile.endswith('.int'):
            next(f); next(f)
        lines = f.readlines()
        for line in lines:
            if line and line[0].isalpha():
                continue
            data = line.split()
            theta, counts = float(data[0]), float(data[1])
            vinkel.append(theta)
            intensitet.append(counts)
    intensitet_norm = [i/max(intensitet) for i in intensitet]
    plt.plot(vinkel, intensitet_norm, label = datafile, *args, **kwargs)
    return vinkel, intensitet_norm

plt.figure(figsize=(16,9))
read_n_plot('NaCl_data.xy', 'k', '--', lw = 1.0)
plt.legend(loc='best')
plt.xlabel(r'$2\theta$')
plt.xlim(0, 65)
plt.ylabel('Intensitet (a.u.)')
plt.tick_params(left=None)
plt.yticks([])
plt.show()

Example below uses standard powder XRD data for NaCl. It seems the '--' argument for linestyle didn't get through at all. The legend says there are two plots.

NaCl XRD data duplicate:

NaCl XRD data duplicate

CodePudding user response:

By referring to the official document of matplotlib.pyplot.plot(), we can find that linestyle is a keyword argument. This is why your code doesn't work as you expected. Try replace '--' with ls='--'.

  • Related