1
votes

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?

2

2 Answers

1
votes

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.

0
votes

I couldn't find a fully formed answer to this, so I thought it would be worth posting the workaround that I used:

from pptx.oxml.xmlchemy import OxmlElement

def SubElement(parent, tagname, **kwargs):
        element = OxmlElement(tagname)
        element.attrib.update(kwargs)
        parent.append(element)
        return element

def manuallySetLegendPosition(
                chart,
                x,
                y,
                w,
                h
                ):
    ## Inside layout, add manualLayout
    L = chart.legend._element.get_or_add_layout()
    mL = L.get_or_add_manualLayout()
    ## Add xMode and yMode and set vals to edge
    xM = SubElement(mL, 'c:xMode', val="edge")
    xY = SubElement(mL, 'c:yMode', val="edge")
    ## Add x, value is between -1 and 1 as a proportion of the chart width
    ##    point of reference on the legend is its centre, not top left
    xE = SubElement(mL, 'c:x', val=str(x))
    ## Add y, same concept as above
    yE = SubElement(mL, 'c:y', val=str(y))
    ## Add w, legend height as a proportion of chart height
    wE = SubElement(mL, 'c:w', val=str(w))
    ## Add h, same concept as above
    hE = SubElement(mL, 'c:h', val=str(h))