Skip to content

Instantly share code, notes, and snippets.

@drorhilman
Last active January 17, 2024 17:48
Show Gist options
  • Save drorhilman/c5ae2f5d6661ea12fd2b5d0c078f9700 to your computer and use it in GitHub Desktop.
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!
# -- consts --
ECHARTS_CDN = "https://cdn.jsdelivr.net/npm/echarts@5.3.2/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))
@drorhilman
Copy link
Author

The 'main' function demonstrates how to use this in jupyter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment