2

I want to use the same color cycle when plotting two pandas dataframes whose columns are the same but represent a different experiment. For example,

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

f1 = lambda x: (x/1)**2
f2 = lambda x: (x/2)**2
f3 = lambda x: (x/3)**2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x), 
                     'f2': f2(x), 
                     'f3': f3(x)})
exp2 = exp1 * 1.5

fig, ax = plt.subplots()

exp1.plot(ax=ax)
exp2.plot(ax=ax, style='--', legend=False)

Gives a figure that looks like:

enter image description here

The second plot command continues where the color cycle left off after the first one. What is the best way to 'reset' the color cycle between successive plotting commands of pandas DataFrames?

pbreach
  • 16,049
  • 27
  • 82
  • 120

1 Answers1

1

As well as the above mentioned answer, it's also worth mentioning that you can always choose your own custom colours, and then use that set for both plots.

from itertools import cycle, islice

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

f1 = lambda x: (x / 1) ** 2
f2 = lambda x: (x / 2) ** 2
f3 = lambda x: (x / 3) ** 2

x = np.linspace(0, 1, 100)

exp1 = pd.DataFrame({'f1': f1(x),
                     'f2': f2(x),
                     'f3': f3(x)})
exp2 = exp1 * 1.5

custom_colours = list(islice(cycle(["b", "g", "r", "c", "m", 'k']), None, len(exp1)))

fig, ax = plt.subplots()

exp1.plot(ax=ax, color=custom_colours)
exp2.plot(ax=ax, style='--', legend=False, color=custom_colours)
Batman
  • 8,571
  • 7
  • 41
  • 80