如何在 Python 的 plt 中获得最新的绘制线的颜色

我没有指定颜色就绘制了一条线(想想 plt.plot (x,y))。 假设颜色变成蓝色。

问: 如何从 plt 对象获得这种颜色,以便将其放入变量中?

看起来很接近(也可能是解决方案) :

p = plt.plot(x,y)
color = p[0].get_color()

最新问题: 我不确定我是否理解“0”索引: p [0]总是访问最近的绘制线吗?

75095 次浏览

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

For regular plt.plot, doing item.get_color() on each element of the list it returns will get you the colors of each line.

But other plot functions, like plt.scatter, will return a Collection. For a Collection, you can call result.get_facecolor(). This will return an array of color values of the foreground colors of the elements. So if they're all the same color (as they are when you make a scatter plot with just X and Y values), result.get_facecolor()[0] will suffice.

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