thosphor
thosphor

Reputation: 2781

Labelling and coloring plots inside loop - matplotlib

I'm plotting multiple hysteresis loops from multiple files in the same axis using a for loop, and I'm wondering how to have a different label and colour for each loop. Each loop is actually made up of two lines. The relevant code is:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

filelist = ['file1', 'file2', 'file3']

fig = plt.figure()
axes = fig.add_subplot(111)

for item in filelist:
    filename = item
    #import hyst files
    up = pd.read_csv(filename)
    up.columns = ['Field','Moment','Temperature']

    upcut = up2[:cut_loc -1] #cuts the file in 2
    down = up2[cut_loc +1:]

    upcutsrt = (upcut.sort(['Field']))

    upcutsrt.plot(x='Field', y='Moment', ax=axes)
    down.plot(x='Field', y='Moment', ax=axes)

ax1.set_xlabel('Magnetic Field', fontsize = 20, labelpad = 15)
ax1.set_ylabel('Magnetic Moment', fontsize=20, labelpad = 15)

plt.show()

So this plots 3 different hysteresis curves on the same axes with the same axes labels and scale and everything. Unfortunately though, all the lines are the same colour. I would like to have each curve (up and down from file) to have a different colour and a different label but I'm at a loss as to how to do it.

Upvotes: 2

Views: 1159

Answers (1)

Alvaro Fuentes
Alvaro Fuentes

Reputation: 17455

Well first you need a list of colors, one per file:

colors = ['red', 'green', 'blue']

then modify the for loop:

for item,col in zip(filelist,colors):

and finally plot using the colors:

    upcutsrt.plot(x='Field', y='Moment', ax=axes, color=col)
    down.plot(x='Field', y='Moment', ax=axes, color=col)

Upvotes: 2

Related Questions