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

如何仅用Pandas和Matplotlib将DataFrame与柱状图导出至同一文件?

仅用Pandas和Matplotlib实现DataFrame与柱状图同文件导出

可以仅依靠Pandas和Matplotlib完成需求,导出为PDF是最直接的方案,无需额外依赖。核心思路是用Matplotlib的PDFPages工具,将柱状图和DataFrame表格绘制到同一个PDF文件中;如果需要HTML,也可以通过Pandas导出表格HTML、Matplotlib导出图片后手动拼接,但PDF方案更简洁无额外文件。

实现代码(PDF方案)

from pandas import DataFrame as df
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PDFPages

# 输入数据
dictionary = {'C': [0.0000, 0.0000, 0.0000], 'V': [0.0000, 0.3940, 0.0000],
              'S': [0.0000, 0.0660, 0.0000], 'I': [94.3160, 0.0000, 0.0000],
              'D': [0.0000, 6.7720, 7.4920], 'CV': [5.6410, 0.0000, 6.5660],
              'ID': [0.0080, 52.2240, 85.3500]}

data_frame = df.from_dict(dictionary, orient='index', columns=['CP1', 'C2', 'C3'])

# 创建PDF对象
with PDFPages('result.pdf') as pdf:
    # 上下布局的子图,容纳图表和表格
    fig, (ax1, ax2) = plt.subplots(nrows=2, ncols=1, figsize=(8, 10))
    
    # 绘制堆叠柱状图
    data_frame.plot.bar(title='Percentage use', stacked=True, ax=ax1)
    ax1.set_xlabel('name')
    ax1.set_ylabel('usage in percentage')
    ax1.legend(bbox_to_anchor=(1.05, 1), loc='upper left')  # 调整图例位置避免遮挡
    
    # 绘制DataFrame表格
    ax2.axis('off')  # 隐藏表格的坐标轴
    table = ax2.table(cellText=data_frame.values,
                      rowLabels=data_frame.index,
                      colLabels=data_frame.columns,
                      loc='center')
    table.auto_set_font_size(False)
    table.set_fontsize(10)
    table.scale(1.2, 1.5)  # 调整表格大小
    
    # 调整子图间距,避免内容重叠
    plt.tight_layout()
    
    # 将当前图保存到PDF
    pdf.savefig(fig, bbox_inches='tight')
    plt.close()

代码说明

  1. PDFPages:负责创建和管理PDF文件,通过with语句自动处理文件的打开/关闭,无需手动操作。
  2. 子图布局:用subplots创建上下两个子图,分别放置柱状图和表格,确保内容在同一页展示。
  3. 表格绘制:利用Matplotlib的table函数,直接传入DataFrame的行/列标签和数值,通过调整字体、缩放比例优化表格显示效果。
  4. 图例优化:将柱状图的图例移到图外,避免遮挡数据区域。

HTML方案(无需额外库)

如果需要HTML格式,可分三步实现:

  1. 用Pandas导出DataFrame为HTML代码:html_table = data_frame.to_html()
  2. 用Matplotlib保存柱状图为图片:
    plot = data_frame.plot.bar(title='Percentage use ', stacked=True)
    plot.set_xlabel('name')
    plot.set_ylabel('usage in percentage')
    plt.savefig('bar_plot.png', bbox_inches='tight')
    plt.close()
    
  3. 手动编写HTML文件,将图片和表格代码拼接:
    <!DOCTYPE html>
    <html>
    <body>
        <h1>Percentage Use</h1>
        <img src="bar_plot.png" alt="Stacked Bar Chart" style="max-width: 800px;">
        <div style="margin-top: 20px;">
            {{ 这里粘贴上面生成的html_table代码 }}
        </div>
    </body>
    </html>
    

这种方案需要同时分发HTML文件和图片文件,不如PDF方案便捷。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 13:15:32