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

如何在Matplotlib图表中嵌入Pandas样式化LaTeX表格

解决Matplotlib嵌入LaTeX表格显示异常的问题

问题原因

  1. 破坏LaTeX结构:你将生成的LaTeX源码中的换行符替换为空格,导致所有LaTeX命令挤在一起,LaTeX解析器无法正确识别表格的结构。
  2. 不恰当的表格环境:默认生成的table浮动环境在Matplotlib的文本渲染中不被支持,应该使用纯tabular环境。
  3. 坐标系选择不当:ax.text基于坐标轴坐标系,容易被图表元素遮挡,且位置调整不够灵活。
  4. 字体大小未适配:默认字体过大,导致表格显示溢出或排版混乱。

修改后的完整代码

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame(np.random.randn(10000, 4) * np.array([1, 2, 2, 0.5]) + np.array([0, 4, 9, 11]), 
                  columns=['first', 'second', 'third', 'fourth'])

stats = df.describe()
stats.index = [idx.replace('%', 'p') for idx in stats.index]

styled = stats.style\
    .background_gradient(cmap=sns.blend_palette(['xkcd:red', 'white', 'xkcd:green'], as_cmap=True), 
                         vmin=-15, vmax=15, 
                         subset=pd.IndexSlice[['mean', 'min', '25p', '50p', '75p', 'max'], :])\
    .background_gradient(cmap=sns.blend_palette(['white', 'xkcd:purple'], as_cmap=True), 
                         vmin=0, vmax=3, subset=pd.IndexSlice['std', :])\
    .format(lambda v: f'{v:0.2f}')\
    .format(lambda v: f'{v:0.0f}', subset=pd.IndexSlice['count', :])

# 生成纯tabular环境的LaTeX代码,保留原换行结构
s = styled.to_latex(
    clines="skip-last;data",
    convert_css=True,
    table_env='tabular',  # 替换默认的table浮动环境为tabular
    multicol_align="|c|",
    hrules=True
)

plt.rc('text', usetex=True)
plt.rc('text.latex', preamble=r'\usepackage{booktabs} \usepackage{etoolbox} \usepackage{multirow} \usepackage[table]{xcolor} \usepackage{colortbl} \usepackage{siunitx} \usepackage{graphics}')
plt.rc('font', size=8)  # 调整全局字体大小适配表格

fig, ax = plt.subplots(1, 1, figsize=(10, 6))
df.plot(kind='hist', ax=ax, histtype='stepfilled', alpha=0.4, bins=50)
ax.set_xlim([-6, 15])
ax.legend(loc='upper right')

# 使用figure坐标系放置表格,避免被遮挡,设置合适的对齐方式
fig.text(0.02, 0.98, s, ha='left', va='top', fontsize=8)

plt.show()

关键修改点说明

  • 保留LaTeX换行:移除.replace('\n', ' '),确保LaTeX代码结构完整,解析器能正确识别表格的行与命令。
  • 使用tabular环境:通过table_env='tabular'生成纯表格环境,避免Matplotlib不支持的浮动table环境。
  • 切换到figure坐标系:用fig.text替代ax.text,基于整个画布的0-1坐标系定位,更灵活且不易被图表元素遮挡。
  • 调整字体大小:全局设置字体大小为8,确保表格在图表中显示完整且排版美观。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 02:07:02