• Stars
    star
    507
  • Rank 87,068 (Top 2 %)
  • Language
    Python
  • License
    MIT License
  • Created over 4 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A Streamlit component to render ECharts.

Streamlit - ECharts

Streamlit App

A Streamlit component to display ECharts.

Install

pip install streamlit-echarts

Usage

This library provides 2 functions to display echarts :

  • st_echarts to display charts from ECharts json options as Python dicts
  • st_pyecharts to display charts from Pyecharts instances

Check out the demo and source code for more examples.

st_echarts example

from streamlit_echarts import st_echarts

options = {
    "xAxis": {
        "type": "category",
        "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    "yAxis": {"type": "value"},
    "series": [
        {"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "line"}
    ],
}
st_echarts(options=options)

st_pyecharts example

from pyecharts import options as opts
from pyecharts.charts import Bar
from streamlit_echarts import st_pyecharts

b = (
    Bar()
    .add_xaxis(["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"])
    .add_yaxis(
        "2017-2018 Revenue in (billion $)", [21.2, 20.4, 10.3, 6.08, 4, 2.2]
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(
            title="Top cloud providers 2018", subtitle="2017-2018 Revenue"
        ),
        toolbox_opts=opts.ToolboxOpts(),
    )
)
st_pyecharts(b)

API

st_echarts API

st_echarts(
    options: Dict
    theme: Union[str, Dict]
    events: Dict[str, str]
    height: str
    width: str
    renderer: str
    map: Map
    key: str
)
  • options : Python dictionary that resembles the JSON counterpart of echarts options. For example the basic line chart in JS :
// JS code
option = {
  xAxis: {
    type: "category",
    data: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
  },
  yAxis: { type: "value" },
  series: [{ data: [820, 932, 901, 934, 1290, 1330, 1320], type: "line" }],
};

is represented in Python :

# Python code
option = {
    "xAxis": {
        "type": "category",
        "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    "yAxis": { "type": "value" },
    "series": [
        {"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "line" }
    ],
}
  • theme : echarts theme. You can specify built-int themes or pass over style configuration as a Python dict.
  • events : Python dictionary which maps an event to a Js function as string. For example :
{
    "click": "function(params) { console.log(params.name) }"
}

will get mapped to :

myChart.on("click", function (params) {
  console.log(params.name);
});

Return values from events are sent back to Python, for example:

option = {
    "xAxis": {
        "type": "category",
        "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
    },
    "yAxis": { "type": "value" },
    "series": [
        {"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "line" }
    ],
}
events = {
    "click": "function(params) { console.log(params.name); return params.name }",
    "dblclick":"function(params) { return [params.type, params.name, params.value] }"
}
value = st_echarts(option, events=events)
st.write(value)  # shows name on bar click and type+name+value on bar double click

The JS code needs to be a one-liner. You can use Javascript minifiers like https://javascript-minifier.com/ or https://www.minifier.org/ to transform your Javascript code to a one-liner.

  • height / width : size of the div wrapper
  • map : register a map using the dedicated Map class
from streamlit_echarts import Map
with open("USA.json", "r") as f:
    map = Map(
        "USA",
        json.loads(f.read()),
        {
            "Alaska": {"left": -131, "top": 25, "width": 15},
            "Hawaii": {"left": -110, "top": 28, "width": 5},
            "Puerto Rico": {"left": -76, "top": 26, "width": 2},
        },
    )
options = {...}
st_echarts(options, map=map)

You'll find a lot of GeoJSON data inside the source code of echarts-countries-js.

  • renderer : SVG or canvas
  • key : assign a fixed identity if you want to change its arguments over time and not have it be re-created.

st_pyecharts API

def st_pyecharts(
    chart: Base
    theme: Union[str, Dict]
    events: Dict[str, str]
    height: str
    width: str
    renderer: str
    map: Map
    key: str
)
  • chart : Pyecharts instance

The docs for the remaining inputs are the same as its st_echarts counterpart.

Development

Install

  • JS side
cd frontend
npm install
  • Python side
conda create -n streamlit-echarts python=3.7
conda activate streamlit-echarts
pip install -e .

Run

Both webpack dev server and Streamlit need to run for development mode.

  • JS side
cd frontend
npm run start
  • Python side

Demo example is on https://github.com/andfanilo/streamlit-echarts-demo.

git clone https://github.com/andfanilo/streamlit-echarts-demo
cd streamlit-echarts-demo/
streamlit run app.py

Caveats

Theme definition

  • Defining the theme in Pyecharts when instantiating chart like Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)) does not work, you need to call theme in st_pyecharts(c, theme=ThemeType.LIGHT).

On Javascript functions

This library also provides the JsCode util class directly from pyecharts.

This class is used to indicate javascript code by wrapping it with a specific placeholder. On the custom component side, we parse every value in options looking for this specific placeholder to determine whether a value is a JS function.

As such, if you want to pass JS functions as strings in your options, you should use the corresponding JsCode module to wrap code with this placeholder :

  • In Python dicts representing the JSON option counterpart, wrap any JS string function with streamlit_echarts.JsCode by calling JsCode(function).js_code. It's a smaller version of pyecharts.commons.utils.JsCode so you don't need to install pyecharts to use it.
series: [
    {
        type: 'scatter', // this is scatter chart
        itemStyle: {
            opacity: 0.8
        },
        symbolSize: JsCode("function (val) { return val[2] * 40;}").js_code,
        data: [["14.616","7.241","0.896"],["3.958","5.701","0.955"],["2.768","8.971","0.669"],["9.051","9.710","0.171"],["14.046","4.182","0.536"],["12.295","1.429","0.962"],["4.417","8.167","0.113"],["0.492","4.771","0.785"],["7.632","2.605","0.645"],["14.242","5.042","0.368"]]
    }
]
  • In Pyecharts, use pyecharts.commons.utils.JsCode directly, JsCode automatically calls .js_code when dumping options.
.set_series_opts(
        label_opts=opts.LabelOpts(
            position="right",
            formatter=JsCode(
                "function(x){return Number(x.data.percent * 100).toFixed() + '%';}"
            ),
        )
    )

Note: you need the JS string to be on one-line. You can use Javascript minifiers like https://javascript-minifier.com/ or https://www.minifier.org/ to transform your Javascript code to a one-liner.

st_pyecharts VS using pyecharts with components.html

While this package provides a st_pyecharts method, if you're using pyecharts you can directly embed your pyecharts visualization inside st.html by passing the output of the chart's .render_embed().

from pyecharts.charts import Bar
from pyecharts import options as opts
import streamlit.components.v1 as components

c = (Bar()
    .add_xaxis(["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"])
    .add_yaxis('2017-2018 Revenue in (billion $)', [21.2, 20.4, 10.3, 6.08, 4, 2.2])
    .set_global_opts(title_opts=opts.TitleOpts(title="Top cloud providers 2018", subtitle="2017-2018 Revenue"),
                     toolbox_opts=opts.ToolboxOpts())
    .render_embed() # generate a local HTML file
)
components.html(c, width=1000, height=1000)

Using st_pyecharts is still something you would want if you need to change data regularly without remounting the component, check for examples examples/app_pyecharts.py for Chart with randomization example.

Credits

Support me

Buy Me A Coffee

More Repositories

1

streamlit-drawable-canvas

Do you like Quick, Draw? Well what if you could train/predict doodles drawn inside Streamlit? Also draws lines, circles and boxes over background images for annotation.
TypeScript
557
star
2

streamlit-lottie

Streamlit component to render Lottie animations
Python
164
star
3

social-media-tutorials

Code dumps of Youtube/Twitter tutorials
Jupyter Notebook
160
star
4

pyspark-tutorial

Jupyter notebooks for pyspark tutorials given at University
Jupyter Notebook
99
star
5

streamlit-component-template-vue

Vue 2/3 template for Streamlit Components
Vue
81
star
6

streamlit-d3-demo

D3 in React in Streamlit tech demo
TypeScript
77
star
7

fastapi-vue-crud

Testing a project with a FastAPI backend and Vue.js frontend in the same project
Vue
76
star
8

streamlit-echarts-demo

Demo for Streamlit ECharts component
Python
76
star
9

streamlit-drawable-canvas-demo

Streamlit Share demo for Drawable Canvas
Python
47
star
10

streamlit-light-leaflet

Streamlit quick & dirty Leaflet component that sends back coordinates on map click
TypeScript
42
star
11

writing-with-gpt2

Reproducing "Writing with Transformer" demo, using aitextgen/FastAPI in backend, Quill/React in frontend
JavaScript
28
star
12

streamlit-cytoscapejs

Cytoscape.js wrapper for Streamlit
Python
28
star
13

streamlit-custom-slider

Streamlit custom slider - Code for the Streamlit Component Tutorial blog post
Python
27
star
14

streamlit-nginx-basicauth

Reverse-proxy NGinx doing Basic Authentication, passing Auth user through Websocket headers and Streamlit extracting auth login from websocket headers to customize page per user logging in.
Dockerfile
16
star
15

streamlit_scatterplot_selection

Companion to https://dev.to/andfanilo/streamlit-components-scatterplot-with-selection-using-plotly-js-3d7n
Python
15
star
16

quickdraw-minigame

A Quickdraw minigame prototype with Vue.js and Tensorflow.js/TFVis - https://andfanilo.github.io/quickdraw-minigame/
JavaScript
14
star
17

streamlit-google-authentication-tests

Exploring different ways for Google Authentication in Streamlit
Python
13
star
18

ddsp-streamlit-ui

Streamlit version for the DDSP timbre transfer demo.
Python
11
star
19

regression-streamlit-viz

Streamlit app for somewhat arbitrary regression
Python
11
star
20

streamlit-lottie-demo

Python
11
star
21

streamlit-plotly-component-tutorial

JavaScript
11
star
22

pyspark-streamlit-tutorial

Python
9
star
23

cookiecutter-kaggle

A cookiecutter Conda template to bootstrap your Kaggle projects (and any data science Python projects anyway)
Python
8
star
24

streamlit-midi-to-wav

Streamlit app to convert MIDI to WAV with FluidSynth.
Python
8
star
25

streamlit-css-button

Pimp your Streamlit button through CSS
Python
8
star
26

streamlit-named-entity-svelte

Streamlit Component in Svelte, imitates the named recognition demo from Prodigy.
TypeScript
7
star
27

streamlit-ama

Python
7
star
28

cloudera-quickstartvm-tutorial

Hadoop tutorial for university in Cloudera Quickstart VM
7
star
29

streamlit-weekly-roundup-api

Browse through all links from Streamlit Weekly Roundup posts
Python
6
star
30

spark-project-template

A reusable Maven Apache Spark template project in Scala
Scala
5
star
31

s4a_cats_grid

A Streamlit app for a grid of random cute cats !
Python
4
star
32

ieee-fraud-detection

Analysis for IEEE Fraud Detection kaggle competition
Jupyter Notebook
4
star
33

streamlit-sandbox

A whole bunch of one-shot code I create to solve issues on the Streamlit forum
Python
4
star
34

streamlit-chat-with-youtube-playlist

Very Quick "Chat with a Youtube Playlist" Streamlit App
Python
3
star
35

streamlit-echarts-events-demo

Python
3
star
36

hdp-tutorial

Hadoop tutorial using the Hortonworks Data Platform for university lecture.
Python
3
star
37

pyspark-interactive-lecture

A RISE Pyspark lecture
Jupyter Notebook
3
star
38

ml-in-pl-23

Python
2
star
39

wikipediaforecast

Code for "Web Traffic Time Series Forecasting" Kaggle competition
Jupyter Notebook
2
star
40

regression-ipywidgets-viz

Ipywidget notebooks for an internal WL talk about ML, optimization and regression
Jupyter Notebook
2
star
41

s4a-python-challenges

PoC Streamlit Education
Python
2
star
42

s4a-local-video

Display local video on Streamlit Share
Python
2
star
43

andfanilo

It's a secret to everybody
2
star
44

s4a-selenium

Test Selenium + Firefox on Streamlit Share
Python
2
star
45

superstore-dashboard-streamlit

Streamlit Dashboard over Superstore Data stored in Postgres Docker container. With SQLAlchemy + Plotly Express
Python
2
star
46

streamlit-pedalboard-demo

Streamlit Pedalboard demo
Python
1
star
47

s4a-webrtc-colornamer

Python
1
star
48

arjs-test

Test ar.js example on Github Pages
HTML
1
star
49

s4a-css-hacking

Streamlit CSS hacks
Python
1
star
50

personal-codepen

WIP: A Vue.js codepen clone
Vue
1
star
51

devbox-vagrant

My development box on Vagrant/VirtualBox
Shell
1
star
52

kaggle-titanic-spark

Analysis of the Kaggle Titanic dataset using Spark
Scala
1
star
53

curious_notebooks

Jupyter notebooks I wrote for testing the latest Python librairies. Expect data analytics, visualisation, and the occasional strange package.
Jupyter Notebook
1
star
54

test-fasthtml-dashboard

A scrappy test of FastHTML + TailwindCSS on a live dashboard usecase.
Python
1
star
55

house-prices-advanced-regression-techniques

Some of my work on House Prices: Advanced Regression Techniques Kaggle competition
HTML
1
star
56

lyon2-docker-demo

Python
1
star
57

lyon2

Python
1
star
58

lyon2-nosql-demo

1
star