_chart.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. from __future__ import absolute_import
  2. # Copyright (c) 2010-2019 openpyxl
  3. from collections import OrderedDict
  4. from openpyxl.compat import basestring
  5. from openpyxl.descriptors import (
  6. Typed,
  7. Integer,
  8. Alias,
  9. MinMax,
  10. Bool,
  11. Set,
  12. )
  13. from openpyxl.descriptors.nested import Nested
  14. from openpyxl.descriptors.sequence import NestedSequence, ValueSequence
  15. from openpyxl.descriptors.serialisable import Serialisable
  16. from openpyxl.xml.constants import PACKAGE_CHARTS
  17. from ._3d import _3DBase
  18. from .data_source import AxDataSource, NumRef
  19. from .layout import Layout
  20. from .legend import Legend
  21. from .reference import Reference
  22. from .series_factory import SeriesFactory
  23. from .series import attribute_mapping
  24. from .shapes import GraphicalProperties
  25. from .title import TitleDescriptor
  26. class AxId(Serialisable):
  27. val = Integer()
  28. def __init__(self, val):
  29. self.val = val
  30. def PlotArea():
  31. from .chartspace import PlotArea
  32. return PlotArea()
  33. class ChartBase(Serialisable):
  34. """
  35. Base class for all charts
  36. """
  37. legend = Typed(expected_type=Legend, allow_none=True)
  38. layout = Typed(expected_type=Layout, allow_none=True)
  39. roundedCorners = Bool(allow_none=True)
  40. axId = ValueSequence(expected_type=int)
  41. visible_cells_only = Bool(allow_none=True)
  42. display_blanks = Set(values=['span', 'gap', 'zero'])
  43. _series_type = ""
  44. ser = ()
  45. series = Alias('ser')
  46. title = TitleDescriptor()
  47. anchor = "E15" # default anchor position
  48. width = 15 # in cm, approx 5 rows
  49. height = 7.5 # in cm, approx 14 rows
  50. _id = 1
  51. _path = "/xl/charts/chart{0}.xml"
  52. style = MinMax(allow_none=True, min=1, max=48)
  53. mime_type = "application/vnd.openxmlformats-officedocument.drawingml.chart+xml"
  54. graphical_properties = Typed(expected_type=GraphicalProperties, allow_none=True)
  55. __elements__ = ()
  56. def __init__(self, axId=(), **kw):
  57. self._charts = [self]
  58. self.title = None
  59. self.layout = None
  60. self.roundedCorners = None
  61. self.legend = Legend()
  62. self.graphical_properties = None
  63. self.style = None
  64. self.plot_area = PlotArea()
  65. self.axId = axId
  66. self.display_blanks = 'gap'
  67. self.pivotSource = None
  68. self.pivotFormats = ()
  69. self.visible_cells_only = True
  70. self.idx_base = 0
  71. super(ChartBase, self).__init__()
  72. def __hash__(self):
  73. """
  74. Just need to check for identity
  75. """
  76. return id(self)
  77. def __iadd__(self, other):
  78. """
  79. Combine the chart with another one
  80. """
  81. if not isinstance(other, ChartBase):
  82. raise TypeError("Only other charts can be added")
  83. self._charts.append(other)
  84. return self
  85. def to_tree(self, namespace=None, tagname=None, idx=None):
  86. self.axId = [id for id in self._axes]
  87. if self.ser is not None:
  88. for s in self.ser:
  89. s.__elements__ = attribute_mapping[self._series_type]
  90. return super(ChartBase, self).to_tree(tagname, idx)
  91. def _write(self):
  92. from .chartspace import ChartSpace, ChartContainer
  93. self.plot_area.layout = self.layout
  94. idx_base = self.idx_base
  95. for chart in self._charts:
  96. if chart not in self.plot_area._charts:
  97. chart.idx_base = idx_base
  98. idx_base += len(chart.series)
  99. self.plot_area._charts = self._charts
  100. container = ChartContainer(plotArea=self.plot_area, legend=self.legend, title=self.title)
  101. if isinstance(chart, _3DBase):
  102. container.view3D = chart.view3D
  103. container.floor = chart.floor
  104. container.sideWall = chart.sideWall
  105. container.backWall = chart.backWall
  106. container.plotVisOnly = self.visible_cells_only
  107. container.dispBlanksAs = self.display_blanks
  108. container.pivotFmts = self.pivotFormats
  109. cs = ChartSpace(chart=container)
  110. cs.style = self.style
  111. cs.roundedCorners = self.roundedCorners
  112. cs.pivotSource = self.pivotSource
  113. return cs.to_tree()
  114. @property
  115. def _axes(self):
  116. x = getattr(self, "x_axis", None)
  117. y = getattr(self, "y_axis", None)
  118. z = getattr(self, "z_axis", None)
  119. return OrderedDict([(axis.axId, axis) for axis in (x, y, z) if axis])
  120. def set_categories(self, labels):
  121. """
  122. Set the categories / x-axis values
  123. """
  124. if not isinstance(labels, Reference):
  125. labels = Reference(range_string=labels)
  126. for s in self.ser:
  127. s.cat = AxDataSource(numRef=NumRef(f=labels))
  128. def add_data(self, data, from_rows=False, titles_from_data=False):
  129. """
  130. Add a range of data in a single pass.
  131. The default is to treat each column as a data series.
  132. """
  133. if not isinstance(data, Reference):
  134. data = Reference(range_string=data)
  135. if from_rows:
  136. values = data.rows
  137. else:
  138. values = data.cols
  139. for ref in values:
  140. series = SeriesFactory(ref, title_from_data=titles_from_data)
  141. self.series.append(series)
  142. def append(self, value):
  143. """Append a data series to the chart"""
  144. l = self.series[:]
  145. l.append(value)
  146. self.series = l
  147. @property
  148. def path(self):
  149. return self._path.format(self._id)