Skip to content

Commit 8bb3612

Browse files
committed
Refactor savefig functionality to save plots of multiple strategies and multiple figures (numfigs > 1)
1 parent 072ab8b commit 8bb3612

2 files changed

Lines changed: 27 additions & 6 deletions

File tree

backtrader/cerebro.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -865,7 +865,8 @@ def getbroker(self):
865865
broker = property(getbroker, setbroker)
866866

867867
def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
868-
savefig=False, figfilename='backtrader-plot-%i.png',
868+
savefig=False, figfilename='backtrader-plot-{j}-{i}.png',
869+
width=16, height=9, dpi=300, tight=True,
869870
**kwargs):
870871
'''
871872
Plots the strategies inside cerebro
@@ -886,6 +887,21 @@ def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
886887
``end``: An index to the datetime line array of the strategy or a
887888
``datetime.date``, ``datetime.datetime`` instance indicating the end
888889
of the plot
890+
891+
``savefig``: set to ``True`` to save to a file rather than plot
892+
893+
``figfilename``: name of the file. Use ``{j}`` in the name for the
894+
strategy index to which the figure corresponds and use ``{i}`` to
895+
insert figure number if multiple figures are being used per strategy
896+
plot
897+
898+
``width``: in inches of the saved figure
899+
900+
``height``: in inches of the saved figure
901+
902+
``dpi``: quality in dots per inches of the saved figure
903+
904+
``tight``: only save actual content and not the frame of the figure
889905
'''
890906
if self._exactbars > 0:
891907
return
@@ -914,7 +930,12 @@ def plot(self, plotter=None, numfigs=1, iplot=True, start=None, end=None,
914930
figs.append(rfig)
915931

916932
if savefig:
917-
plotter.savefig(figfilename % len(figs))
933+
for j, stratfigs in enumerate(figs):
934+
for i, fig in enumerate(stratfigs):
935+
plotter.savefig(fig,
936+
filename=figfilename.format(j=j, i=i),
937+
width=width, height=height, dpi=dpi,
938+
tight=tight)
918939
else:
919940
plotter.show()
920941
return figs

backtrader/plot/plot.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -757,10 +757,10 @@ def plotdata(self, data, indicators):
757757
def show(self):
758758
self.mpyplot.show()
759759

760-
def savefig(self, filename='backtrader-plot.png'):
761-
fig = self.mpyplot.gcf()
762-
fig.set_size_inches(16, 9)
763-
self.mpyplot.savefig(filename, dpi=300, bbox_inches='tight')
760+
def savefig(self, fig, filename, width=16, height=9, dpi=300, tight=True):
761+
fig.set_size_inches(width, height)
762+
bbox_inches = 'tight' * tight or None
763+
fig.savefig(filename, dpi=dpi, bbox_inches=bbox_inches)
764764

765765
def sortdataindicators(self, strategy):
766766
# These lists/dictionaries hold the subplots that go above each data

0 commit comments

Comments
 (0)