Search code examples
pythonformattinglabelstreamlitecharts

How to format labels in echarts in streamlit


I want my echart bar chart data labels rounded to 2 digits. I know there is a formatter function for this:

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

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

But: In streamlit I have to put echart options into quotation marks, and this breaks the above mentioned formatter function. This is my python code:

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,
            )

The formatter itself works when I uncomment 'formatter': '{@Y}'

enter image description here

but not when I uncomment 'formatter': {function(param) {return param.data.toFixed(2);}}

How can I format/round the labels to 2 digits?


Solution

  • You just need to wrap the formatter's function in a 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