从两个不连续的列创建折线图

Create a line chart from two non-contiguous columns

我必须根据三列的第一列和第三列创建折线图 sheet。

例如

Gender Responses  Index
Female   325      2.52
Male     243      3.15
Other    127      4.21

也就是说,值应该取自索引,而标签取自性别。所以我写了

chart = excel.Charts.Add(After=wb.Sheets(wb.Sheets.Count))
chart.Name = "LineChart"
chart.Type = win32c.xlLine
chart.HasTitle = True
chart.ChartTitle.Text = "Just a title"
chart.SetSourceData(dist_ws.Range("A1:A4", "C1:C4"))

但它不起作用。该范围包含所有三列,无论如何我都会得到一个异常。我也试过了

chart.SetSourceData(dist_ws.Range("A1:A4, C1:C4"))

chart.SetSourceData(dist_ws.Range("A2:A4, C1:C4"))

但它不起作用。所以我需要单独设置源数据(在 C2:C4 中,C1 中有系列名称)和 X 轴标签(在 A2:A4 中)。

知道我做错了什么吗?

我用完全不同的方式解决了这个问题:

# FIRST, I create a new sheet to allocate chart
chart_ws = wb.Sheets.Add(After=wb.Sheets(wb.Sheets.Count))
chart_ws.Name = "Anyname"

# SECOND, I add a line chart in it
chart_ws.Shapes.AddChart2(-1, win32c.xlLineMarkers, 0, 0, 560, 320).Select()
chart = wb.ActiveChart
chart.HasTitle = True
chart.ChartTitle.Text = "Any title"

# THIRD, I create a series for data
series = chart.SeriesCollection().NewSeries()

# FOURTH, I set the two ranges for labels and values
# Warning: ranges do NOT includes headers (A1 and C1)
# A1 is used to name the series
series.XValues = dist_ws.Range("A2:A4")
series.Values = dist_ws.Range("C2:C4")
series.Name = dist_ws.Range("A1").Value

有效。