问题描述
目前我正在这样做:
my_list = []
for x,y in zip(xs,ys):
my_list.extend(ax.plot(x,y,linestyle = '',marker = 'o'))
因为我想分别访问每个 line2d 对象。有没有办法调用 ax.plot 或 ax.scatter 一次并以某种方式获取所有 line2d 的列表对象?
解决方法
您正在尝试访问保存绘图中线条的容器。绘图有许多容器,例如图形和轴。这实际上很容易做到,只需绘制线条,然后使用 ax.lines 访问它们。后者将是 Line2D 对象的列表。
这是一个简单的示例,通过访问绘图中的线条并使用 matplotlib.lines.Line2D.set_color() 函数来演示此容器功能。
import matplotlib.pyplot as plt
import numpy as np
fig,ax = plt.subplots(figsize=(12,8)) # define fig and axes
x = np.linspace(-20,20) # make some x values between -20 and 20
f_x = np.sin(x/4) # make some y values that are f(x) = sin(x/4)
g_x = np.cos(x/4) # make some y values that are g(x) = cos(x/4)
ax.plot(x,f_x,linewidth=2.5,label='f(x)') # plot f(x)
ax.plot(x,g_x,label='g(x)') # plot g(x)
ax.lines[0].set_color('blue')
ax.lines[1].set_color('red')
#add titles,x labels,y labels,legend
title = ax.set_title('Example plot',fontsize=14,fontweight='bold')
xlabels = ax.set_xlabel('x_values')
ylabels = ax.set_ylabel('y_values')
legend = ax.legend(fontsize=14)
您可以通过查看 matplotlib 文档中的 Artist Tutorial 了解有关容器的更多信息。