在 matplotlib 中设置线条颜色的常用方法是在绘图命令中指定。这可以通过数据后面的字符串来完成,例如"r-"
红线,或明确说明color
争论。
import matplotlib.pyplot as plt
plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line
plt.show()
另请参阅绘图命令的文档 http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot.
如果您已经有某种颜色的线条,您可以使用lines2D.set_color()
method.
line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")
Setting the color of a line in a pandas plot is also best done at the point of creating the plot:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line
plt.show()
如果您想稍后更改此颜色,可以通过以下方式进行
plt.gca().get_lines()[0].set_color("black")
这将为您提供当前活动轴的第一行(可能是唯一一行)。
如果图中有更多轴,您可以循环它们
for ax in plt.gcf().axes:
ax.get_lines()[0].set_color("black")
如果你有更多的线,你也可以循环它们。