如何在streamlit中格式化echarts中的标签

问题描述 投票:0回答:1

我希望我的echart条形图数据标签四舍五入到2位数字。 我知道有一个格式化程序功能:

label: {
        show: true,
        formatter: function(param) {
          return param.data.toFixed(2);
        }
      },

https://echarts.apache.org/en/option.html#series-bar.label.formatter
eChart 沙箱

但是:在streamlit中我必须将echart选项放入引号中,这破坏了上面提到的格式化程序功能。 这是我的Python代码:

import streamlit as st   
from streamlit_echarts import st_echarts
import pandas as pd

data = {
  "X": ['A','B','C'],
  "Y": [420.2456245, 380.2456254742, 390.2345624564],
}
df = pd.DataFrame(data)
dfec = [df.columns.tolist()] + df.values.tolist()
#dfec

ec_option = {
            "dataset": [
                {"source":
                    dfec
                }
            ],
            "xAxis": {
                "type": "category",
            },
            "yAxis": {
            },
            "series": [
                {"name": "Y", "type": "bar", "symbol": "none", "encode": {"x": 'name', "y": 'previous'},
                 'label': {
                    'show': 1,
                    'position': 'top',
                    #'formatter': '{@Y}'
                    #'formatter': {function(param) {return param.data.toFixed(2);}}
                  },
                },
            ],
            "legend": {
            },
        }

st_echarts(options=ec_option,
            )

当我取消注释时,格式化程序本身就可以工作 '格式化程序':'{@Y}'

enter image description here

但当我取消评论时则不然 '格式化程序': {function(param) {return param.data.toFixed(2);}}

如何将标签格式化/四舍五入为 2 位数字?

python formatting label streamlit echarts
1个回答
0
投票

您只需将格式化程序的 string 包装成

JsCode
:

from pyecharts.commons.utils import JsCode

ec_option = {
    "dataset": [{"source": dfec}],
    "xAxis": {
        "type": "category",
    },
    "yAxis": {},
    "series": [
        {
            "name": "Y",
            "type": "bar",
            "symbol": "none",
            "encode": {"x": "name", "y": "previous"},
            "label": {
                "show": 1,
                "position": "top",
                "formatter": JsCode(
                    "function(param) {return Number(param.data[1]).toFixed(2);}"
                ).js_code,
            },
        },
    ],
    "legend": {},
}

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.