首页 > 解决方案 > 将 pygal 值配置与 DateTimeLine 一起使用

问题描述

我正在绘制一些 CPU 时间统计数据,并希望能够注释某些值。我想为此使用pygal 的值配置,但这似乎无法与我正在使用的DateTimeLine图表结合使用。

def generate_cpu_time_plot(csv_file_path, output_file):
    user = []
    system = []
    with open(csv_file_path, encoding="utf-8") as csv_file:
        reader = csv.DictReader(csv_file)
        for row in reader:
            time = datetime.fromtimestamp(int(row['time_millis']) / 1000)
            user.append((time, {
                'value': float(row['cpu_time_user'])
            }))
            system.append((time, {
                'value': float(row['cpu_time_system'])
            }))

    chart = pygal.DateTimeLine(x_label_rotation=35,
                               x_value_formatter=lambda dt: dt.strftime(
                                   '%d/%m/%Y %H:%M'), x_title='Time',
                               y_title='CPU time',
                               title=os.path.basename(csv_file_path))
    chart.add("User", user)
    chart.add("System", system)
    chart.render_to_file(output_file)

这给了我一个 TypeError:TypeError: '<' not supported between instances of 'dict' and 'dict'

有没有办法让这种组合发挥作用?如果我直接使用浮点数,没有字典,这很好。

标签: pythonpygal

解决方案


包含您提供给 XY 图表的 x 和 y 值的元组就是。当您使用dict提供值的格式时,您需要将value属性设置为此元组。

目前,您的代码尝试将dicty 值放入元组中。将值附加到usersystem列表的行更改为以下内容应该可以修复它:

user.append({'value': (time, float(row['cpu_time_user']))})
system.append({'value': (time, float(row['cpu_time_system']))})

推荐阅读