我正在尝试放弃 matlab 并使用 python + matplotlib 代替。然而,我还没有真正弄清楚 matplotlib 等价于 matlab 'handles' 的是什么。这里有一些 matlab 代码,我在其中返回句柄,以便我可以更改某些属性。使用 matplotlib 的这段代码的等价物是什么?我经常在 matlab 中使用句柄的“Tag”属性,并使用“findobj”。这也可以用 matplotlib 来完成吗?
% create figure and return figure handle
h = figure();
% add a plot and tag it so we can find the handle later
plot(1:10, 1:10, 'Tag', 'dummy')
% add a legend
my_legend = legend('a line')
% change figure name
set(h, 'name', 'myfigure')
% find current axes
my_axis = gca();
% change xlimits
set(my_axis, 'XLim', [0 5])
% find the plot object generated above and modify YData
set(findobj('Tag', 'dummy'), 'YData', repmat(10, 1, 10))
最佳答案
有一个findobj方法也是matplotlib:
import matplotlib.pyplot as plt
import numpy as np
h = plt.figure()
plt.plot(range(1,11), range(1,11), gid='dummy')
my_legend = plt.legend(['a line'])
plt.title('myfigure') # not sure if this is the same as set(h, 'name', 'myfigure')
my_axis = plt.gca()
my_axis.set_xlim(0,5)
for p in set(h.findobj(lambda x: x.get_gid()=='dummy')):
p.set_ydata(np.ones(10)*10.0)
plt.show()
请注意,plt.plot
中的 gid
参数通常由 matplotlib 使用(仅)当后端设置为“svg”时。它使用 gid
作为某些分组元素的 id
属性(例如 line2d
、patch
、text
)。
关于python - 该matlab代码对应的matplotlib代码是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7537967/