我有一个有3个数字的应用程序,并动态地更改它们。目前,通过使用add_subplot()
来完成这项工作已经很好了。但现在我必须使我的图表更复杂,并且需要使用subplot2grid()
self.figure1 = plt.figure()
self.canvas1 = FigureCanvas(self.figure1)
self.graphtoolbar1 = NavigationToolbar(self.canvas1, frameGraph1)
self.figure3 = plt.figure()
self.canvas3 = FigureCanvas(self.figure3)
self.graphtoolbar3 = NavigationToolbar(self.canvas3, frameGraph3)
self.figure4 = plt.figure()
self.canvas4 = FigureCanvas(self.figure4)
self.graphtoolbar4 = NavigationToolbar(self.canvas4, frameGraph4)
以下是添加它的代码,以及我到目前为止所获得的代码。
#ax = self.figure1.add_subplot(2,1,1) <---- What I used to do
fig = self.figure1
ax = plt.subplot2grid((4,4), (0,0), rowspan=3, colspan=4) # <--- what I'm trying to do
ax.hold(False)
ax.plot(df['Close'], 'b-')
ax.legend(loc=0)
ax.set_xlabel("Date")
ax.set_ylabel("Price")
ax.grid(True)
for tick in ax.get_xticklabels():
tick.set_rotation(20)
self.canvas1.draw()
以上将其添加到图4.可能是因为这是由plt实例化的最新版本。但我喜欢上述内容,将subplot2grid添加到self.figure1
,同时仍具有以前的动态功能。
答案 0 :(得分:2)
查看matplotlib
的源代码,subplot2grid
- 函数按以下方式定义:
def subplot2grid(shape, loc, rowspan=1, colspan=1, **kwargs):
"""
Create a subplot in a grid. The grid is specified by *shape*, at
location of *loc*, spanning *rowspan*, *colspan* cells in each
direction. The index for loc is 0-based. ::
subplot2grid(shape, loc, rowspan=1, colspan=1)
is identical to ::
gridspec=GridSpec(shape[0], shape[2])
subplotspec=gridspec.new_subplotspec(loc, rowspan, colspan)
subplot(subplotspec)
"""
fig = gcf() # <-------- HERE
s1, s2 = shape
subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
rowspan=rowspan,
colspan=colspan)
a = fig.add_subplot(subplotspec, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
if other==a: continue
if bbox.fully_overlaps(other.bbox):
byebye.append(other)
for ax in byebye: delaxes(ax)
draw_if_interactive()
return a
正如您在代码段中的评论“HERE”中所看到的,它仅使用有效数字,即fig = gcf()
(gcf是“获取当前数字”的缩写)。
通过稍微修改功能并将其放入脚本中,可以轻松实现目标。
from matplotlib.gridspec import GridSpec
from matplotlib.backends import pylab_setup
_backend_mod, new_figure_manager, draw_if_interactive, _show = pylab_setup()
def my_subplot2grid(fig, shape, loc, rowspan=1, colspan=1, **kwargs):
s1, s2 = shape
subplotspec = GridSpec(s1, s2).new_subplotspec(loc,
rowspan=rowspan,
colspan=colspan)
a = fig.add_subplot(subplotspec, **kwargs)
bbox = a.bbox
byebye = []
for other in fig.axes:
if other==a: continue
if bbox.fully_overlaps(other.bbox):
byebye.append(other)
for ax in byebye: delaxes(ax)
draw_if_interactive()
return a
现在应该可以做你的事情,修改你的函数调用
ax = plt.my_subplot2grid(self.figure1, (4,4), (0,0), rowspan=3, colspan=4)
希望它有所帮助!