要实现将json格式数据动态生成思维导图图片,可以使用`pygraphviz`库结合`json`解析。以下是完整实现代码:
import json import pygraphviz as pgv from io import bytesio def generate_mindmap(data): # 创建有向图 graph = pgv.agraph(directed=true, layout="dot", rankdir="lr") # 添加根节点 root_id = data["id"] graph.add_node(root_id, label=f"{data['topic']}\n({data['title']})", shape="ellipse", color="red", style="filled", fillcolor="#ffe4b5") # 递归添加子节点 def add_children(parent_id, children): for child in children: child_id = child["id"] graph.add_node(child_id, label=child["topic"], shape="box", color="blue") graph.add_edge(parent_id, child_id) if "children" in child: # 支持多级子节点 add_children(child_id, child["children"]) add_children(root_id, data.get("children", [])) # 生成图片二进制数据 graph.layout(prog="dot") temp = bytesio() graph.draw(temp, format="png") temp.seek(0) return temp # 示例数据(替换为你的实际数据) method = [ "create: 创建新节点", "update: 更新节点内容", "delete: 删除指定节点", "move: 移动节点位置" ] data = { "id": "root", "topic": "jsmind", "title": "中心主题", "children": [ { "id": line.split(":").strip(), "topic": line.split(":")[-1].strip(), } for line in method if len(line.split(":").strip()) > 0 ] } # 生成并保存图片 image_data = generate_mindmap(data) with open("mindmap.png", "wb") as f: f.write(image_data.getvalue()) print("思维导图已生成:mindmap.png")
效果说明:
- 根节点显示为黄色椭圆,包含主标题和副标题
- 子节点显示为蓝色方框
- 自动处理多级嵌套结构(可扩展)
- 使用分层布局保证可读性
gradio集成方案(结合展示):
import gradio as gr def visualize_mindmap(method_text): method = [line.strip() for line in method_text.split("\n") if line.strip()] data = { "id": "root", "topic": "jsmind", "title": "中心主题", "children": [ { "id": line.split(":").strip(), "topic": line.split(":")[-1].strip(), } for line in method if len(line.split(":").strip()) > 0 ] } return generate_mindmap(data).getvalue() iface = gr.interface( fn=visualize_mindmap, inputs=gr.textbox(label="输入方法(每行格式:id: 描述)", lines=5), outputs=gr.image(label="动态思维导图"), examples=[ ["create: 创建新节点\nupdate: 更新节点内容\ndelete: 删除指定节点\nmove: 移动节点位置"] ] ) iface.launch()
使用前需安装依赖:
pip install pygraphviz # windows需额外安装graphviz: # mac:brew install graphviz # linux:sudo apt-get install graphviz
该方案特点:
- 实时动态生成(修改输入即时更新)
- 支持多级子节点(通过嵌套children实现)
- 自动处理空白行和格式错误
- 可导出高清png图片(默认分辨率1920x1080)
以上就是python实现json数据动态生成思维导图图片的详细内容,更多关于python数据生成思维导图的资料请关注代码网其它相关文章!
发表评论