Commit 96625901 authored by CharlieC's avatar CharlieC
Browse files

Sort chart series by order when reading.

Resolves #1666

--HG--
branch : 3.0
parent b5da740da421
# Copyright (c) 2010-2021 openpyxl # Copyright (c) 2010-2021 openpyxl
from collections import OrderedDict from collections import OrderedDict
from operator import attrgetter
from openpyxl.descriptors import ( from openpyxl.descriptors import (
Typed, Typed,
...@@ -107,6 +108,18 @@ class ChartBase(Serialisable): ...@@ -107,6 +108,18 @@ class ChartBase(Serialisable):
return super(ChartBase, self).to_tree(tagname, idx) return super(ChartBase, self).to_tree(tagname, idx)
def _reindex(self):
"""
Normalise and rebase series: sort by order and then rebase order
"""
# sort data series in order and rebase
ds = sorted(self.series, key=attrgetter("order"))
for idx, s in enumerate(ds):
s.order = idx
self.series = ds
def _write(self): def _write(self):
from .chartspace import ChartSpace, ChartContainer from .chartspace import ChartSpace, ChartContainer
self.plot_area.layout = self.layout self.plot_area.layout = self.layout
......
...@@ -24,5 +24,6 @@ def read_chart(chartspace): ...@@ -24,5 +24,6 @@ def read_chart(chartspace):
chart.pivotSource = cs.pivotSource chart.pivotSource = cs.pivotSource
chart.pivotFormats = cs.chart.pivotFmts chart.pivotFormats = cs.chart.pivotFmts
chart.idx_base = min((s.idx for s in chart.series), default=0) chart.idx_base = min((s.idx for s in chart.series), default=0)
chart._reindex()
return chart return chart
...@@ -162,10 +162,12 @@ class Series(Serialisable): ...@@ -162,10 +162,12 @@ class Series(Serialisable):
self.smooth = smooth self.smooth = smooth
self.explosion = explosion self.explosion = explosion
def to_tree(self, tagname=None, idx=None): def to_tree(self, tagname=None, idx=None):
"""The index can need rebasing"""
if idx is not None: if idx is not None:
if self.order == self.idx: if self.order == self.idx:
self.order = idx self.order = idx # rebase the order if the index has been rebased
self.idx = idx self.idx = idx
return super(Series, self).to_tree(tagname) return super(Series, self).to_tree(tagname)
......
...@@ -189,3 +189,24 @@ class TestChartBase: ...@@ -189,3 +189,24 @@ class TestChartBase:
xml = tostring(tree) xml = tostring(tree)
diff = compare_xml(xml, expected) diff = compare_xml(xml, expected)
assert diff is None, diff assert diff is None, diff
def test_reindex(self, ChartBase):
chart = ChartBase()
chart.ser = []
chart.add_data("Sheet!D1:D4")
chart.add_data("Sheet!B1:B4")
chart.add_data("Sheet!C1:C4")
chart.add_data("Sheet!A1:A4")
orders = [40, 20, 34, 11]
for o, s in zip(orders, chart.series):
s.order = o
ordered = [s.order for s in chart.series]
assert ordered == [40, 20, 34, 11]
chart._reindex()
reordered = [s.order for s in chart.series]
assert reordered == [0, 1, 2, 3]
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment