LineChart.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # Copyright 2015-2017 Espressif Systems (Shanghai) PTE LTD
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http:#www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from collections import OrderedDict
  15. import pyecharts.options as opts
  16. from pyecharts.charts import Line
  17. def draw_line_chart(file_name, title, x_label, y_label, data_series, range_list):
  18. """
  19. draw line chart and save to file.
  20. :param file_name: abs/relative file name to save chart figure
  21. :param title: chart title
  22. :param x_label: x-axis label
  23. :param y_label: y-axis label
  24. :param data_series: a dict {"name": data}. data is a dict.
  25. :param range_list: a list of x-axis range
  26. """
  27. line = Line()
  28. # echarts do not support minus number for x axis, convert to string
  29. _range_list = [str(x) for x in range_list]
  30. line.add_xaxis(_range_list)
  31. for item in data_series:
  32. _data = OrderedDict.fromkeys(_range_list, None)
  33. for key in data_series[item]:
  34. _data[str(key)] = data_series[item][key]
  35. _data = list(_data.values())
  36. try:
  37. legend = item + ' (max: {:.02f})'.format(max([x for x in _data if x]))
  38. except TypeError:
  39. legend = item
  40. line.add_yaxis(legend, _data, is_smooth=True, is_connect_nones=True,
  41. label_opts=opts.LabelOpts(is_show=False))
  42. line.set_global_opts(
  43. datazoom_opts=opts.DataZoomOpts(range_start=0, range_end=100),
  44. title_opts=opts.TitleOpts(title=title, pos_left='center'),
  45. legend_opts=opts.LegendOpts(pos_top='10%', pos_left='right', orient='vertical'),
  46. tooltip_opts=opts.TooltipOpts(trigger='axis'),
  47. xaxis_opts=opts.AxisOpts(type_='category', name=x_label, splitline_opts=opts.SplitLineOpts(is_show=True)),
  48. yaxis_opts=opts.AxisOpts(type_='value', name=y_label,
  49. axistick_opts=opts.AxisTickOpts(is_show=True),
  50. splitline_opts=opts.SplitLineOpts(is_show=True)),
  51. )
  52. line.render(file_name)