Skip to content

Commit 33ec12b

Browse files
committed
Improve legend presentation in sameaxis mode
1 parent 9b9ae17 commit 33ec12b

1 file changed

Lines changed: 17 additions & 9 deletions

File tree

backtrader/plot/plot.py

Lines changed: 17 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ def __init__(self, sch):
6464
self.coloridx = collections.defaultdict(lambda: -1)
6565
self.handles = collections.defaultdict(list)
6666
self.labels = collections.defaultdict(list)
67+
self.legpos = collections.defaultdict(int)
6768

6869
self.prop = mfontmgr.FontProperties(size=self.sch.subtxtsize)
6970

@@ -683,32 +684,37 @@ def plotdata(self, data, indicators):
683684
self.plotind(data, ind, subinds=self.dplotsover[ind], masterax=ax)
684685

685686
handles, labels = ax.get_legend_handles_labels()
687+
a = axdatamaster or ax
686688
if handles:
687689
# put data and volume legend entries in the 1st positions
688690
# because they are "collections" they are considered after Line2D
689691
# for the legend entries, which is not our desire
690692
# if self.pinf.sch.volume and self.pinf.sch.voloverlay:
693+
694+
ai = self.pinf.legpos[a]
691695
if self.pinf.sch.volume and voloverlay:
692696
if volplot:
693697
# even if volume plot was requested, there may be no volume
694-
labels.insert(0, vollabel)
695-
handles.insert(0, volplot)
698+
labels.insert(ai, vollabel)
699+
handles.insert(ai, volplot)
696700

697701
didx = labels.index(datalabel)
698-
labels.insert(0, labels.pop(didx))
699-
handles.insert(0, handles.pop(didx))
702+
labels.insert(ai, labels.pop(didx))
703+
handles.insert(ai, handles.pop(didx))
700704

701705
if axdatamaster is None:
702706
self.pinf.handles[ax] = handles
703707
self.pinf.labels[ax] = labels
704708
else:
705-
self.pinf.handles[axdatamaster].extend(handles)
706-
self.pinf.labels[axdatamaster].extend(labels)
709+
self.pinf.handles[axdatamaster] = handles
710+
self.pinf.labels[axdatamaster] = labels
711+
# self.pinf.handles[axdatamaster].extend(handles)
712+
# self.pinf.labels[axdatamaster].extend(labels)
707713

708-
h = self.pinf.handles[axdatamaster or ax]
709-
l = self.pinf.labels[axdatamaster or ax]
714+
h = self.pinf.handles[a]
715+
l = self.pinf.labels[a]
710716

711-
axlegend = axdatamaster or ax
717+
axlegend = a
712718
legend = axlegend.legend(h, l,
713719
loc='upper left',
714720
frameon=False, shadow=False,
@@ -727,6 +733,8 @@ def plotdata(self, data, indicators):
727733
upinds=self.dplotsup[downind],
728734
downinds=self.dplotsdown[downind])
729735

736+
self.pinf.legpos[a] = len(self.pinf.handles[a])
737+
730738
def show(self):
731739
self.mpyplot.show()
732740

0 commit comments

Comments
 (0)