您看到的Figure (200x200)
是__repr__
matplotlib Figure 类的字符串。它是该 python 对象的文本表示(与您在执行时看到的相同print(fig)
)。
相反,您想要的是在表格中有一个实际的图像。一个简单的选择是将 matplotlib 图形保存为 png 图像,创建一个 html 标记,<img src="some.png" />
从而显示表格。
import pandas as pd
import numpy as np;np.random.seed(1)
import matplotlib.pyplot as plt
import matplotlib.colors
df = pd.DataFrame({"info" : np.random.randint(0,10,10),
"status" : np.random.randint(0,3,10)})
cmap = matplotlib.colors.ListedColormap(["crimson","orange","limegreen"])
def createFigure(i):
fig, ax = plt.subplots(figsize=(.4,.4))
fig.subplots_adjust(0,0,1,1)
ax.axis("off")
ax.axis([0,1,0,1])
c = plt.Circle((.5,.5), .4, color=cmap(i))
ax.add_patch(c)
ax.text(.5,.5, str(i), ha="center", va="center")
return fig
def mapping(i):
fig = createFigure(i)
fname = "data/map_{}.png".format(i)
fig.savefig(fname)
imgstr = '<img src="{}" /> '.format(fname)
return imgstr
df['image'] = df['status'].map(mapping)
df.to_html('test.html', escape=False)
这样做的缺点是您有很多图像保存在磁盘的某个位置。如果不需要,您可以将编码为 base64 的图像存储在 html 文件中,<img src="data:image/png;base64,iVBORw0KGgoAAAAN..." />
.
import pandas as pd
import numpy as np;np.random.seed(1)
import matplotlib.pyplot as plt
import matplotlib.colors
from io import BytesIO
import base64
df = pd.DataFrame({"info" : np.random.randint(0,10,10),
"status" : np.random.randint(0,3,10)})
cmap = matplotlib.colors.ListedColormap(["crimson","orange","limegreen"])
def createFigure(i):
fig, ax = plt.subplots(figsize=(.4,.4))
fig.subplots_adjust(0,0,1,1)
ax.axis("off")
ax.axis([0,1,0,1])
c = plt.Circle((.5,.5), .4, color=cmap(i))
ax.add_patch(c)
ax.text(.5,.5, str(i), ha="center", va="center")
return fig
def fig2inlinehtml(fig,i):
figfile = BytesIO()
fig.savefig(figfile, format='png')
figfile.seek(0)
# for python 2.7:
#figdata_png = base64.b64encode(figfile.getvalue())
# for python 3.x:
figdata_png = base64.b64encode(figfile.getvalue()).decode()
imgstr = '<img src="data:image/png;base64,{}" />'.format(figdata_png)
return imgstr
def mapping(i):
fig = createFigure(i)
return fig2inlinehtml(fig,i)
with pd.option_context('display.max_colwidth', -1):
df.to_html('test.html', escape=False, formatters=dict(status=mapping))
输出看起来相同,但没有图像保存到磁盘。
这在 Jupyter Notebook 中也可以很好地工作,只需稍作修改,
from IPython.display import HTML
# ...
pd.set_option('display.max_colwidth', -1)
HTML(df.to_html(escape=False, formatters=dict(status=mapping)))