返回

使用 Highcharts Stock 在 Python 中创建多线折线图:分步指南

python

使用 Highcharts Stock 在 Python 中创建多线折线图

简介

Highcharts Stock 是一个用于创建交互式财务图表的高级库。在本教程中,我们将指导您使用 Highcharts Stock 在 Python 中创建包含多条折线图的图表,以显示两家公司的收盘价。

先决条件

  • Python 3.6 或更高版本
  • pip
  • Highcharts Stock 1.5.0(从 PyPI 安装)

安装 Highcharts Stock

使用 pip 安装 Highcharts Stock:

pip install highcharts_stock

创建数据集

创建包含两家公司收盘价的数据集:

data = [
    {
        'name': '公司 A',
        'data': [10.0, 11.5, 12.3, 11.8, 12.0, 13.5, 14.3]
    },
    {
        'name': '公司 B',
        'data': [15.0, 16.5, 17.3, 16.8, 17.0, 18.5, 19.3]
    }
]

创建图表

使用 Highcharts Stock 创建图表:

import highcharts_stock as hcs

chart = hcs.Highstock()

options = {
    'chart': {
        'type': 'line'
    },
    'title': {
        'text': '两家公司的收盘价'
    },
    'xAxis': {
        'type': 'datetime'
    },
    'yAxis': {
        'title': {
            'text': '收盘价'
        }
    },
    'series': data
}

chart.add_series(options)

显示图表

显示图表:

chart.show()

完整代码

以下是完整的 Python 代码:

import highcharts_stock as hcs

data = [
    {
        'name': '公司 A',
        'data': [10.0, 11.5, 12.3, 11.8, 12.0, 13.5, 14.3]
    },
    {
        'name': '公司 B',
        'data': [15.0, 16.5, 17.3, 16.8, 17.0, 18.5, 19.3]
    }
]

chart = hcs.Highstock()

options = {
    'chart': {
        'type': 'line'
    },
    'title': {
        'text': '两家公司的收盘价'
    },
    'xAxis': {
        'type': 'datetime'
    },
    'yAxis': {
        'title': {
            'text': '收盘价'
        }
    },
    'series': data
}

chart.add_series(options)

chart.show()

常见问题解答

1. 如何更改折线图的颜色?

series 字典中,将 color 参数设置为所需的顏色。例如:

'series': [
    {
        'name': '公司 A',
        'color': 'red',
        'data': [...]
    },
    {
        'name': '公司 B',
        'color': 'blue',
        'data': [...]
    }
]

2. 如何添加网格线?

xAxisyAxis 字典中,设置 gridLineWidth 参数为非零值。例如:

'xAxis': {
    'gridLineWidth': 1
},
'yAxis': {
    'gridLineWidth': 1
}

3. 如何缩放图表?

使用 navigatorscrollbar 选项。例如:

'navigator': {
    'enabled': True
},
'scrollbar': {
    'enabled': True
}

4. 如何添加图例?

legend 字典中,设置 enabled 参数为 True。例如:

'legend': {
    'enabled': True
}

5. 如何导出图表?

使用 exporting 选项。例如:

'exporting': {
    'enabled': True
}