如何使用openpyxl更改图表中数据标签的布局

时间:2019-05-24 03:11:02

标签: python-3.x openpyxl

我已经知道更改图表中图例布局的方法

legend.layout = ManualLayout()

但是它不适用于数据标签,我想知道如何在图表中手动更改数据标签。

import openpyxl
from openpyxl import Workbook, load_workbook
from openpyxl.chart import ScatterChart, Series, Reference
from openpyxl.chart.layout import Layout, ManualLayout
wb = Workbook()
ws = wb.active
rows = [
    ['Size', 'Batch 1', 'Batch 2'],
    [2, 40, 30],
    [3, 40, 25],
    [4, 50, 30],
    [5, 30, 25],
    [6, 25, 35],
    [7, 20, 40],
]
for row in rows:
    ws.append(row)
ch1 = ScatterChart()
xvalues = Reference(ws, min_col=1, min_row=2, max_row=7)
for i in range(2, 4):
    values = Reference(ws, min_col=i, min_row=1, max_row=7)
    series = Series(values, xvalues, title_from_data=True)
    ch1.series.append(series)

# show the last data label of first line
series_1 = ch1.series[0]
series_1.dLbls = openpyxl.chart.label.DataLabelList()
dl = openpyxl.chart.label.DataLabel(idx=5)
dl.showVal = True
dl.spPr = openpyxl.chart.shapes.GraphicalProperties(solidFill='5981B8')
series_1.dLbls.dLbl.append(dl)

# changing the layout of legend 
ch1.legend.layout = openpyxl.chart.layout.Layout(manualLayout=openpyxl.chart.layout.ManualLayout(x=0.41, y=-0.4))

# not work
series_1.dLbls.dLbl[0].layout = openpyxl.chart.layout.Layout(manualLayout=openpyxl.chart.layout.ManualLayout(x=0.41, y=-0.4))

ws.add_chart(ch1, "B10")
wb.save("example.xlsx")

This is the chart created by current code This is the chart I prefer

0 个答案:

没有答案