如何在Jupyter Notebook(iPython)中正确实现两张图片并排显示?
在IPython中并排显示两张PNG图片的解决方法
你遇到的问题其实很常见——直接用本地路径写HTML的src属性时,IPython的前端没办法直接读取本地文件系统里的图片,所以才会只显示占位符。既然你已经确认图片路径没问题,那试试下面这几种靠谱的方法:
方法一:用IPython的Image对象拼接HTML
这种方法利用IPython自带的Image对象生成能被前端识别的HTML片段,再用flex布局实现并排,操作简单且适配IPython环境:
from IPython.display import Image, display, HTML img_A_path = '/path/to/img_A.png' img_B_path = '/path/to/img_B.png' # 创建Image对象,可指定宽度统一两张图的尺寸 img_a = Image(filename=img_A_path, width=300) img_b = Image(filename=img_B_path, width=300) # 用flex布局实现并排,gap参数控制两张图的间距 display(HTML(f"<div style='display:flex; gap:20px;'>{img_a._repr_html_()} {img_b._repr_html_()}</div>"))
方法二:将图片转为Base64内嵌到HTML
把图片编码成Base64格式直接嵌入HTML里,彻底避免路径访问权限的问题,兼容性拉满:
import base64 from IPython.display import HTML, display # 工具函数:将本地图片转为Base64编码 def img_to_base64(img_path): with open(img_path, 'rb') as img_file: return base64.b64encode(img_file.read()).decode() # 转换两张目标图片 img_A_b64 = img_to_base64('/path/to/img_A.png') img_B_b64 = img_to_base64('/path/to/img_B.png') # 用flex布局居中并排显示 html_content = f""" <div style="display: flex; justify-content: center; gap: 30px;"> <img src="data:image/png;base64,{img_A_b64}" width="350"> <img src="data:image/png;base64,{img_B_b64}" width="350"> </div> """ display(HTML(html_content))
方法三:用Matplotlib子图直接显示
既然你已经能用plt.imshow正常显示图片,那直接用Matplotlib的子图功能来并排会更直观,还能自定义标题、隐藏坐标轴:
import matplotlib.pyplot as plt import matplotlib.image as mpimg # 读取本地图片 img_a = mpimg.imread('/path/to/img_A.png') img_b = mpimg.imread('/path/to/img_B.png') # 创建1行2列的子图,figsize控制整体显示尺寸 fig, (ax_left, ax_right) = plt.subplots(1, 2, figsize=(12, 6)) # 显示第一张图并自定义样式 ax_left.imshow(img_a) ax_left.axis('off') # 隐藏坐标轴 ax_left.set_title('图片A') # 显示第二张图并自定义样式 ax_right.imshow(img_b) ax_right.axis('off') ax_right.set_title('图片B') # 自动调整子图间距,避免内容重叠 plt.tight_layout() plt.show()
你之前用HTML表格失败的核心原因是:IPython的前端环境无法直接访问本地文件的绝对路径,上面的方法要么通过IPython内置对象处理路径,要么把图片数据直接嵌入HTML,都能完美解决这个问题。
内容的提问来源于stack exchange,提问作者Kristada673
相关产品推荐
相关产品推荐

