set chart name in Xlwings

徘徊边缘 提交于 2019-12-11 07:36:51

问题


When I plot a chart by xlwings, I can't change chart name. The chart name and legend name are still 'Series 1', but the upper left corner shows 'Feb sales' which is I want

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'
chart.name='Feb sales'
#chart.api.ChartTitle.Text = 'Feb sales'
#chart.delete()

created chart

Is this a known issue? How can I fix this?


回答1:


This should work:

import xlwings as xw

sht = xw.Book().sheets[0]
sht.range('A1').value = list(zip([1, 2, 3, 4]))
chart = sht.charts.add()
chart.set_source_data(sht.range('A1').expand())
chart.chart_type = 'line_markers'

chart.api[1].SetElement(2)  # Place chart title at the top
chart.api[1].ChartTitle.Text = 'Feb sales'  # Change text of the chart title

The expression chart.api returns a tuple with two COM wrappers. I'm not really sure why there are two COM wrappers, but it seems that you need the second one to access the chart. Hence the use of chart.api[1] here.

With the attribute xlwings.Chart.name you can set an excel chart's Name property (as you did in your question's code), but this is not a property that is used for display. To achieve display of text in the chart you need to set the excel chart's ChartTitle property (as done in this answer's code).



来源:https://stackoverflow.com/questions/44910566/set-chart-name-in-xlwings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!