在 AntV G2Plot 中,可以使用 'annotation()' 方法在图形上添加文字注释。具体实现方法如下:

  1. 导入相关模块
from pywebio.output import put_html
from pywebio import start_server

from g2plot import Bar
  1. 创建柱状图对象并设置数据
data = [
    {'year': '2015', 'sales': 123},
    {'year': '2016', 'sales': 234},
    {'year': '2017', 'sales': 345},
    {'year': '2018', 'sales': 456},
    {'year': '2019', 'sales': 567},
    {'year': '2020', 'sales': 678},
]

bar = Bar()
bar.set_options({
    'data': data,
    'xField': 'year',
    'yField': 'sales',
})
  1. 使用 'annotation()' 方法添加文字注释
bar.annotation().text({
    'position': ['2016', 250],
    'content': 'Max Sales',
    'style': {
        'fontSize': 12,
        'textAlign': 'center',
    }
})

在上面的代码中,我们使用 'annotation()' 方法创建了一个注释对象,并使用 'text()' 方法添加了一个文字注释。其中,'position' 参数指定了注释的位置,'content' 参数指定了注释的文本内容,'style' 参数指定了注释的样式。

  1. 在页面中显示图形

最后,我们使用 'put_html()' 函数将图形对象渲染为 HTML 代码,并在浏览器中显示出来。

put_html(bar.render_notebook())

完整代码示例:

from pywebio.output import put_html
from pywebio import start_server

from g2plot import Bar

data = [
    {'year': '2015', 'sales': 123},
    {'year': '2016', 'sales': 234},
    {'year': '2017', 'sales': 345},
    {'year': '2018', 'sales': 456},
    {'year': '2019', 'sales': 567},
    {'year': '2020', 'sales': 678},
]

bar = Bar()
bar.set_options({
    'data': data,
    'xField': 'year',
    'yField': 'sales',
})

bar.annotation().text({
    'position': ['2016', 250],
    'content': 'Max Sales',
    'style': {
        'fontSize': 12,
        'textAlign': 'center',
    }
})

put_html(bar.render_notebook())

运行代码后,就可以在浏览器中看到带有文字注释的柱状图了。

AntV G2Plot 柱状图添加文字注释教程

原文地址: https://www.cveoy.top/t/topic/l2Vp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录