Search code examples
pythonpython-pptx

Custom legend position with python-pptx


I would like to set the legend on a self defined, custom position.

My final goal would be to get the settings of an already existing chart and use the same settings for a new chart.

I read in the docs it's possible to set the legend like this:

(http://python-pptx.readthedocs.io/en/latest/api/enum/XlLegendPosition.html#xllegendposition)

from pptx.enum.chart import XL_LEGEND_POSITION

chart.has_legend = True
chart.legend.position = XL_LEGEND_POSITION.CUSTOM

But I get a ValueError:

ValueError: CUSTOM (-4161) not a member of XL_LEGEND_POSITION enumeration

Did I miss anything or how can I set the legend on a custom position?


Solution

  • The .CUSTOM member of the XL_LEGEND_POSITION is a reporting member only (roughly like "read-only"). It is intended as the value of the Legend.position property when the legend has been manually adjusted (dragged and dropped with the mouse using the UI). Unlike the other members of that enumeration, it is not "assignable" and could not by itself of course set the position to where you wanted it.

    Custom placement of the legend is not yet supported by the python-pptx API. If you wanted to do it you'd have to manipulate the underlying XML with low-level lxml calls. You'd need to understand the relevant XML schema and semantics to know what to do with that XML to produce the result you were after. This sort of thing is commonly called a "workaround function" in python-pptx and python-docx (they work very similarly being based on the same architecture). A Google search on "python-pptx" OR "python-docx" workaround function will find you some examples used for other purposes that you may find helpful if you decide to take that approach.