如何从绘图中获取 matplotlib.lines.Line2D 对象列表?

问题描述

目前我正在这样做:

my_list = []
for x,y in zip(xs,ys):
   my_list.extend(ax.plot(x,y,linestyle = '',marker = 'o'))

因为我想分别访问每个 line2d 对象。有没有办法调用 ax.plotax.scatter 一次并以某种方式获取所有 line2d 的列表对象?

解决方法

您正在尝试访问保存绘图中线条的容器。绘图有许多容器,例如图形和轴。这实际上很容易做到,只需绘制线条,然后使用 ax.lines 访问它们。后者将是 Line2D 对象的列表。

这是一个简单的示例,通过访问绘图中的线条并使用 matplotlib.lines.Line2D.set_color() 函数来演示此容器功能。

Link to plot image (I can't put images in posts yet)

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 了解有关容器的更多信息。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...