Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

图表构建函数支持自定义参数 #60

Open
kinegratii opened this issue Dec 4, 2022 · 0 comments
Open

图表构建函数支持自定义参数 #60

kinegratii opened this issue Dec 4, 2022 · 0 comments
Assignees

Comments

@kinegratii
Copy link
Owner

图表构建函数支持自定义参数,可以根据不同的输入值,加载不同的数据,从而形成多个图表。

以之前的时间轴图表为例子,每次只显示一个年份的数据图表。

@site_obj.register_chart(title='{year}年福建省家庭户类型组成')
def yearly_family(year: int):
    family_types = [
        '一人户', '二人户', '三人户', '四人户', '五人户', '六人户', '七人户', '八人户', '九人户', '十人及其以上'
    ]
    data = [
        [1982, 7.7, 8.2, 12.2, 17.1, 18.4, 14.7, 10.1, 11.6, 0, 0],
        [1990, 5.8, 8.6, 16.8, 23.6, 21.4, 11.8, 5.9, 2.9, 1.4, 1.8],
        [2000, 9.1, 15.5, 25.4, 24.7, 15.8, 5.9, 2.2, 0.8, 0.3, 0.3],
        [2010, 12.1, 17.2, 24.3, 21.7, 13.7, 6.4, 2.6, 1.1, 0.5, 0.4],
        [2020, 27.3, 26.3, 19.4, 14.2, 6.9, 4, 1.1, 0.4, 0.2, 0.2]
    ]
    yearly_data = {item[0]: item[1:] for item in data}
    if year not in yearly_data:
        raise ChartDoesNotExist(f'year={year}')
    year_data = yearly_data[year]
    bar = (
        Bar()
            .add_xaxis(family_types).add_yaxis('百分比(%)', year_data)
            .set_global_opts(title_opts=opts.TitleOpts("福建省家庭户类型构成-{}年".format(year)))
    )
    return bar

说明:

  • year为自定义参数,如未声明类型,默认为 str
  • 如果传入的year找不到对应的数据,抛出 ChartDoesNotExist 异常,web页面显示“找不到图表”的页面。
  • title参数可以使用类似 {year}的模板字符串。

该图表对应的相关引用配置如下(以year=2020例子):

项目 备注
图表URL /chart/year/2020/ 格式:<图表slug>/<参数名称1>/<参数值1>/...
python引用 reverse_lazy('dje_single_chart','yearly_family','year/2020/')
模板引用 {% url 'dje_single_chart' 'yearly_family', 'year/2020/' %}
@kinegratii kinegratii self-assigned this Dec 4, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant