How to get color of most recent plotted line in Python's plt

In your example, p is a list of Line2D object. In that example you have only one line object, p[0]. The following is an example plotting three lines. As more line is added, it is appended to the p. So if you want the color of the last plot, it will be p[-1].get_color().

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(10)
y = np.arange(10)
p = plt.plot(x,y, x,y*2, x,y*3) # make three line plots
type(p) # list
type(p[0]) # <class 'matplotlib.lines.Line2D'>
p[0].get_color() # 'b'
p[1].get_color() # 'g'
p[2].get_color() # 'r'

line plot


If you cannot access or store the return value of the call to plt.plot, you should also be able to use plt.gca().lines[-1].get_color() to access the color of the last line which was added to the plot.

In the following example, I'm creating example data, run curve_fit and show both data and fitted curve in the same color.

import matplotlib.pyplot as plt
import numpy as np
from scipy.optimize import curve_fit

m = 5
n = 3
x = np.arange(m)
y = np.array([i * x + np.random.normal(0, 0.2, len(x)) for i in range(n)])

def f(x, a, b):
    return a * x + b

for y_i in y:
    popt, pcov = curve_fit(f, x, y_i)
    plt.plot(x, y_i, linestyle="", marker="x")
    plt.plot(x, f(x, *popt), color=plt.gca().lines[-1].get_color())
plt.show()

Figure 1