Last active
January 17, 2024 17:48
-
-
Save drorhilman/c5ae2f5d6661ea12fd2b5d0c078f9700 to your computer and use it in GitHub Desktop.
A script to display echarts charts in jupyter notebook, both in notebook and in vscode!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -- consts -- | |
ECHARTS_CDN = "https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min" | |
ECHARTS_REQUIREJS_CONF = f"requirejs.config({{paths: {{echarts: '{ECHARTS_CDN}',}}}});" | |
ECHARTS_TEMPLATE = f""" | |
<div id="{{ID}}" style="width: {{WIDTH}};height:{{HEIGHT}};"></div> | |
<script type="module"> | |
{ECHARTS_REQUIREJS_CONF} | |
requirejs(["echarts"], (echarts) => {{ | |
let myChart = echarts.init(document.getElementById('{{ID}}')); | |
myChart.setOption({{OPTION}}); | |
}} | |
) | |
</script> | |
""" | |
def _multi_replace(string: str, replacements: dict): | |
for k, v in replacements.items(): | |
string = string.replace(k, v) | |
return string | |
def echarts(option: dict, width="800px", height="500px", id='chart'): | |
import json | |
from IPython.display import HTML | |
option = json.dumps(option) | |
h = _multi_replace( | |
ECHARTS_TEMPLATE, {"{WIDTH}": width, "{HEIGHT}": height, "{OPTION}": option, "{ID}": id} | |
) | |
return HTML(h) | |
def main() -> None: | |
from IPython.display import display | |
option = { | |
"xAxis": { | |
"type": "category", | |
"data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], | |
}, | |
"yAxis": {"type": "value"}, | |
"series": [{"data": [150, 230, 224, 218, 135, 147, 260], "type": "line"}], | |
} | |
display(echarts(option)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The 'main' function demonstrates how to use this in jupyter