LineChart.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. # SPDX-FileCopyrightText: 2015-2022 Espressif Systems (Shanghai) CO LTD
  2. # SPDX-License-Identifier: Apache-2.0
  3. from collections import OrderedDict
  4. import pyecharts.options as opts
  5. from pyecharts.charts import Line
  6. def draw_line_chart(file_name, title, x_label, y_label, data_series, range_list):
  7. """
  8. draw line chart and save to file.
  9. :param file_name: abs/relative file name to save chart figure
  10. :param title: chart title
  11. :param x_label: x-axis label
  12. :param y_label: y-axis label
  13. :param data_series: a dict {"name": data}. data is a dict.
  14. :param range_list: a list of x-axis range
  15. """
  16. line = Line()
  17. # echarts do not support minus number for x axis, convert to string
  18. _range_list = [str(x) for x in range_list]
  19. line.add_xaxis(_range_list)
  20. for item in data_series:
  21. _data = OrderedDict.fromkeys(_range_list, None)
  22. for key in data_series[item]:
  23. _data[str(key)] = data_series[item][key]
  24. _data = list(_data.values())
  25. try:
  26. legend = item + ' (max: {:.02f})'.format(max([x for x in _data if x]))
  27. except TypeError:
  28. legend = item
  29. line.add_yaxis(legend, _data, is_smooth=True, is_connect_nones=True,
  30. label_opts=opts.LabelOpts(is_show=False))
  31. line.set_global_opts(
  32. datazoom_opts=opts.DataZoomOpts(range_start=0, range_end=100),
  33. title_opts=opts.TitleOpts(title=title, pos_left='center'),
  34. legend_opts=opts.LegendOpts(pos_top='10%', pos_left='right', orient='vertical'),
  35. tooltip_opts=opts.TooltipOpts(trigger='axis'),
  36. xaxis_opts=opts.AxisOpts(type_='category', name=x_label, splitline_opts=opts.SplitLineOpts(is_show=True)),
  37. yaxis_opts=opts.AxisOpts(type_='value', name=y_label,
  38. axistick_opts=opts.AxisTickOpts(is_show=True),
  39. splitline_opts=opts.SplitLineOpts(is_show=True)),
  40. )
  41. line.render(file_name)