"""蓝色天空网 mbsky.com · pyecharts 离线柱状图实验。"""
from contextlib import chdir
import json
from pathlib import Path
import platform
import sys
import pyecharts
from pyecharts import charts, options as opts
from pyecharts.globals import ThemeType
sys.path.insert(0, str(Path(__file__).resolve().parent))
from mbsky_pychecks import Checks
STATIONS = ["青岚站", "澄湾站", "松桥站", "云汀站", "石泉站"]
OBSERVED = [12, 19, 16, 28, 23]
PLANNED = [15, 17, 18, 25, 24]
CHART_NAMES = ("Line", "Bar", "Scatter", "Pie", "Radar", "HeatMap", "Kline", "Boxplot",
"Map", "WordCloud", "Gauge", "Funnel", "Tree", "TreeMap", "Graph",
"Parallel", "Sankey", "Geo", "Timeline", "Scatter3D", "Bar3D", "Surface3D", "Chord")
THEME_IDS = {
"LIGHT": "light", "WHITE": "white", "WESTEROS": "westeros", "ESSOS": "essos",
"INFOGRAPHIC": "infographic", "MACARONS": "macarons", "SHINE": "shine", "ROMA": "roma",
"VINTAGE": "vintage", "WALDEN": "walden", "WONDERLAND": "wonderland", "ROMANTIC": "romantic",
"DARK": "dark", "CHALK": "chalk", "PURPLE_PASSION": "purple-passion",
}
def base_chart(chart_id, theme=ThemeType.LIGHT):
chart = charts.Bar(init_opts=opts.InitOpts(
width="780px", height="460px", chart_id=chart_id, theme=theme, js_host="vendor/",
page_title="蓝色天空网 · 本地观测量图表", animation_opts=opts.AnimationOpts(animation=False),
))
chart.add_xaxis(STATIONS)
chart.add_yaxis("观测量", OBSERVED, label_opts=opts.LabelOpts(is_show=False))
return chart
def decorate(chart):
chart.set_global_opts(
title_opts=opts.TitleOpts(title="观测量对照", subtitle="单位:次", pos_left="left"),
xaxis_opts=opts.AxisOpts(name="观测站"),
yaxis_opts=opts.AxisOpts(name="观测量(次)"),
legend_opts=opts.LegendOpts(pos_left="center", pos_top="12%"),
)
def generate(folder, check):
with chdir(folder):
basic = base_chart("mbsky_basic")
check.eq("default path name", Path(basic.render()).name, "render.html")
check.eq("default HTML in working directory", Path("render.html").is_file(), True)
check.eq("initial categories and bar values",
(basic.options["xAxis"][0]["data"], basic.options["series"][0]["data"]),
(STATIONS, OBSERVED))
configured = base_chart("mbsky_configured")
decorate(configured)
check.eq("named path returned", Path(configured.render("configured.html")).name, "configured.html")
options = json.loads(configured.dump_options())
check.eq("title, subtitle and axes", (options["title"][0]["text"], options["title"][0]["subtext"],
options["xAxis"][0]["name"], options["yAxis"][0]["name"]),
("观测量对照", "单位:次", "观测站", "观测量(次)"))
dark = base_chart("mbsky_dark", ThemeType.DARK)
decorate(dark)
dark.render("dark.html")
check.eq("theme fixed at initialization", (basic.theme, dark.theme), ("light", "dark"))
check.eq("chart dimensions", (dark.width, dark.height), ("780px", "460px"))
interactive = base_chart("mbsky_interactive")
interactive.add_yaxis("计划量", PLANNED, label_opts=opts.LabelOpts(is_show=False))
interactive.set_global_opts(
title_opts=opts.TitleOpts(title="观测量对照", subtitle="单位:次"),
xaxis_opts=opts.AxisOpts(name="观测站"), yaxis_opts=opts.AxisOpts(name="观测量(次)"),
legend_opts=opts.LegendOpts(pos_left="center", pos_top="12%"),
toolbox_opts=opts.ToolboxOpts(is_show=True, pos_right="4%"),
tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
)
interactive.set_colors(["#176cab", "#d26732"])
interactive.render("interactive.html")
options = json.loads(interactive.dump_options())
check.eq("axis cross tooltip", (options["tooltip"]["trigger"], options["tooltip"]["axisPointer"]["type"]),
("axis", "cross"))
check.eq("toolbox saveAsImage configured",
("saveAsImage" in options["toolbox"]["feature"], options["toolbox"]["show"]), (True, True))
check.eq("legend data and positioning", (options["legend"][0]["data"], options["legend"][0]["left"],
options["legend"][0]["top"]), (["观测量", "计划量"], "center", "12%"))
check.eq("series names and values", [(s["name"],s["data"]) for s in options["series"]],
[("观测量",OBSERVED),("计划量",PLANNED)])
check.eq("custom colors", options["color"], ["#176cab", "#d26732"])
for name in ("render.html", "configured.html", "dark.html", "interactive.html"):
rendered = Path(name).read_text(encoding="utf8")
check.eq("local vendor dependency " + name,
('src="vendor/echarts.min.js"' in rendered, "https://assets.pyecharts.org" in rendered),
(True, False))
def main():
check = Checks()
check.eq("pyecharts version", pyecharts.__version__, "2.1.0")
for name in CHART_NAMES:
constructor = getattr(charts, name)
check.eq("chart constructor " + name, type(constructor()).__name__, name)
for name, identifier in THEME_IDS.items():
chart = base_chart("theme_check", getattr(ThemeType, name))
chart.render_embed()
deps = set(chart.js_dependencies.items)
check.eq("theme registration " + name, (chart.theme, deps), (identifier,
{"echarts"} if identifier in {"light", "white", "dark"} else {"echarts",identifier}))
folder = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else Path(__file__).resolve().parent / "pyecharts-lab"
folder.mkdir(parents=True, exist_ok=True)
generate(folder,check)
check.finish("python-pyecharts",python=platform.python_version(),pyecharts=pyecharts.__version__,
scope="Owned generated HTML; browser behavior is recorded separately. Other chart constructors and theme dependencies only.")
if __name__ == "__main__":
main()
本例需在 Owned generated HTML; browser behavior is recorded separately. Other chart constructors and theme dependencies only. 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Owned generated HTML; browser behavior is recorded separately. Other chart constructors and theme dependencies only.
入口文件:projects/python-lab/python-pyecharts.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
python-pyecharts.py,或下载右侧课程工程包。 - 确认本地已准备 Owned generated HTML; browser behavior is recorded separately. Other chart constructors and theme dependencies only.。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202611a463.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202611a470.zip
课程关联工程包(登记关联82章) · 含当前章节或实例 · mbskycom202612a292.zip