Python的XlsxWriter将文本框插入到图表中

时间:2015-08-13 13:51:46

标签: python excel charts textbox xlsxwriter

我已经创建了一个带有列和线图的组合图表。棘手的部分是在图表中插入一个文本框: 1. X轴标题下方 2.传说下面。

我阅读了文档,发现了worksheet.insert_textbox()。但是,我需要一些图表(如果我正确理解文档,上面的方法适用于工作表,而不是图表)。

我在Windows Vista 64bit上使用Anaconda Python(2.3.0)。

result = pd.ExcelWriter(r'C:/tmp/dev_excel.xlsx', engine='xlsxwriter')

# inserting image with 'xlsxwriter'
workbook = result.book

worksheet = workbook.add_worksheet()
# Add the worksheet data to be plotted.
data = ['Aaaa', 'A2', 'A3', 'A4', 20, 10, 50]
worksheet.write_column('A1', data)

data = ['Bbbbb', 10, 40, 50, 20, 10, 50]
worksheet.write_column('B1', data)

data = ['Cccc', 110, 140, 150, 120, 110, 150]
worksheet.write_column('C1', data)

# Create a new column chart. This will use this as the primary chart.
column_chart = workbook.add_chart({'type': 'column'})

# Configure the data series for the primary chart.
column_chart.add_series({
    'name':       '=Sheet1!B1',
    'categories': '=Sheet1!A2:A7',
    'values':     '=Sheet1!B2:B7',
})

# Create a new column chart. This will use this as the secondary chart.
line_chart = workbook.add_chart({'type': 'line'})

# Configure the data series for the secondary chart.
line_chart.add_series({
    'name':       '=Sheet1!C1',
    'categories': '=Sheet1!A2:A7',
    'values':     '=Sheet1!C2:C7',
    'y2_axis':    True,
})

# Add a chart title and some axis labels.
# ...
column_chart.set_y2_axis({'name': 'Target length (mm)'})

# Combine the charts.
column_chart.combine(line_chart)

# Add a chart title and some axis labels. Note, this is done via the
# primary chart.
column_chart.set_title({ 'name': 'Combined chart - same Y axis'})
column_chart.set_x_axis({'name': 'Test number'})
column_chart.set_y_axis({'name': 'Sample length (mm)'})

# Insert the chart into the worksheet
worksheet.insert_chart('E2', column_chart)

workbook.close()

result.save()

1 个答案:

答案 0 :(得分:0)

  

如果我正确理解文档,则上述方法适用于工作表,而不适用于图表

这是正确的。 XlsxWriter不支持图表中的文本框。

您可以将工作表文本框覆盖在图表上,但它们将是两个独立的对象,并且彼此独立地移动。