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?
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).