You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

IPython.display无法显示LangGraph图表,如何用Matplotlib/Pillow替代?

问题解答

1. IPython能否用于普通Python模块代码?

IPython.display的核心功能是适配Jupyter Notebook/Lab的交互式渲染环境,在普通Python脚本(非Jupyter)中调用它,只会返回对应的IPython.core.display.Image对象,无法直接触发图像渲染显示。所以不能用它在普通Python模块里展示图表。

2. 用Matplotlib绘制并显示LangGraph图表

步骤如下:

  • 安装依赖:
    pip install matplotlib langgraph
    
  • 代码示例:
    import io
    import matplotlib.pyplot as plt
    from langgraph.graph import StateGraph, END
    
    # 定义你的LangGraph图(示例)
    def func(state):
        return state
    graph = StateGraph(dict)
    graph.add_node("node1", func)
    graph.add_edge("node1", END)
    graph.set_entry_point("node1")
    app = graph.compile()
    
    # 导出图表为PNG字节数据
    png_data = app.get_graph().draw_mermaid_png()
    
    # 用Matplotlib加载并显示
    img = plt.imread(io.BytesIO(png_data))
    plt.imshow(img)
    plt.axis('off')  # 隐藏坐标轴
    plt.show()
    

3. 用Pillow绘制并显示LangGraph图表

步骤如下:

  • 安装依赖:
    pip install pillow langgraph
    
  • 代码示例:
    import io
    from PIL import Image
    from langgraph.graph import StateGraph, END
    
    # 定义你的LangGraph图(示例)
    def func(state):
        return state
    graph = StateGraph(dict)
    graph.add_node("node1", func)
    graph.add_edge("node1", END)
    graph.set_entry_point("node1")
    app = graph.compile()
    
    # 导出图表为PNG字节数据
    png_data = app.get_graph().draw_mermaid_png()
    
    # 用Pillow加载并显示
    img = Image.open(io.BytesIO(png_data))
    img.show()
    

无桌面环境适配

如果在无桌面的Ubuntu服务器上运行,无法直接显示图像,可将图片保存到本地:

# Matplotlib保存
plt.savefig("langgraph.png", bbox_inches='tight', pad_inches=0)

# Pillow保存
img.save("langgraph.png")

内容的提问来源于stack exchange,提问作者khteh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 01:02:05