【问题标题】:Create a line chart from two non-contiguous columns从两个不连续的列创建折线图
【发布时间】:2022-01-06 15:14:46
【问题描述】:

我必须从三列工作表的第一列和第三列创建折线图。

例如

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 中)。

知道我做错了什么吗?

【问题讨论】:

  • 猜测,但试试dist_ws.Range("A1:A4,C1:C4"))
  • 我会尽力让你知道的。谢谢。
  • 没有。这是行不通的。我必须找到为折线图分别设置 X 轴的值和类别标签。

标签: excel charts line pywin32


【解决方案1】:

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

# 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

有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-10
    • 2023-04-02
    • 1970-01-01
    • 2014-10-09
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多