使用 Python,如何以编程方式更新 Pygal 图表的数据?

Using Python, how can I update data programmatically for a Pygal chart?

如何使用 Python,以编程方式更新 Pygal 图表的数据?

下面的代码作为静态堆积条形图运行良好,但我不知道如何适应不断变化的值。

Considerations/issues:


import pygal

line_chart = pygal.HorizontalStackedBar()
line_chart.title = 'Application Health'
line_chart.x_labels = ( "cluster05", "cluster04", "cluster03", "cluster02", "cluster01")
line_chart.add('Critical', [2, 5, 4, 1, None])
line_chart.add('Warning',[1, 7, 2, None, 2])
line_chart.add('OK', [25, 30, 19, 20, 25])
line_chart.render_to_file('test_StackedBar.svg')

线型如下class.

>>> type(line_chart.add('OK', [25, 30, 19, 20, 25]))
<class 'pygal.graph.horizontalstackedbar.HorizontalStackedBar'>
>>> 

newData = "21, 55, 35, 82, 47, 70, 60"
line_chart.add('OK',[newData])

TypeError: unsupported operand type(s) for +: 'int' and 'str'

newData = "21, 55, 35, 82, 47, 70, 60"
y = list(newData)
line_chart.add('OK',[y])
line_chart.render_to_file('test_StackedBar.svg')

TypeError: unsupported operand type(s) for +: 'int' and 'list'

你有一个TypeError。它需要一个数字列表。

很容易将变量视为替换: y = [1,2,3] 表示任何有 y 的地方,只需输入 [1,2,3] 即可。因此,当您执行 [y] 时,它会很乐意将其替换为 [[1,2,3]]

你给它一个包含单个字符串的列表: ["21, 55, 35, 82, 47, 70, 60"],然后将其传递到列表中: [["21, 55, 35, 82, 47, 70, 60"]],这不是它所期望的。

它想要一个整数列表:

y = [21, 55, 35, 82, 47, 70, 60]
line_chart.add('OK',y)

要更新图表,您可能必须重建它(我不熟悉 pygal,因此它可能支持就地编辑,但重建总是有效)

def update_chart(crit_values, warning_values, ok_values):
    line_chart = pygal.HorizontalStackedBar()
    line_chart.title = 'Application Health'
    line_chart.x_labels = ( "cluster05", "cluster04", "cluster03", "cluster02", "cluster01")
    line_chart.add('Critical', crit_values)
    line_chart.add('Warning', warning_values)
    line_chart.add('OK', ok_values)
    line_chart.render_to_file('test_StackedBar.svg')

将允许您重建它并为每种类型传递新列表,方法是:

update_chart([2, 5, 4, 1, None], [1, 7, 2, None, 2], [25, 30, 19, 20, 25])update_chart(x, y, z) 其中 x、y、z 是我上面显示的整数列表。