Matplotlib中的数据标签,以及将图形保存为PPTX文件

编程语言 2026-07-08

我在用matplotlib创建可视化图表。到目前为止,我需要用下列数据样本来创建数据标签。

cellvalue1 = [1,2,3,4,5,6,7,8,9,10,11,12,13]
cellvalue2 = [1,2,3]

fig, ax = plt.subplots(figsize=(10, 2))
ax.axis('off')
fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)
plt.plot(data_lyr['Period'],data_lyr['Sum of Sales'], label = '2025', color = 'blue')
plt.plot(data_cyr['Period'],data_cyr['Sum of Sales'], label = '2026', color = 'gray')
plt.gca().set_ylim(ymin=0)
plt.legend()
cellvalue1 = [[f"${val/1_000_000:,.2f}M" for val in data_lyr['Sum of Sales']]]
cellvalue2 = [[f"${val/1_000_000:,.2f}M" for val in data_cyr['Sum of Sales']]]
cellvalue2 = [1, 2, 3];cellvalue2 = [""] * (13 - len(cellvalue2)) + cellvalue2
plt.table(cellText=[cellvalue1,cellvalue2],rowLabels=[str(int(yr)-1),yr],loc='bottom',bbox=[0.0,-0.35,1.0,0.15])

plt.subplots_adjust(bottom= 0.3)
plt.show()

这项工作的最终产物是[数据表]!在此输入图片描述

我想让它分成13列,2026年的其他列若没有数据就保持为空。

完成后,我还想把图保存下来,以便在pptx中使用。提前感谢。

解决方案

为了便于插入到pptx,我通常将图像保存为SVG:

# Use transparent=True for a transparent background (optionnal).
# --> Useful for blending into some pptx templates
plt.savefig('./table.svg', transparent=True)

更一般地说,我不会尝试在同一个坐标轴上同时放置图和表,我会改用两个坐标轴。大致是这样的:

import matplotlib.pyplot as plt
import random as rd

rd.seed(0)

# Dummy data
x = list(range(13))
y1 = [rd.random() for _ in x]
y2 = [rd.random() for _ in x]

# Utility function
def adjust_right(cells: list, length: int = 13):
    return [''] * (length - len(cells)) + cells

# Create figure and axes
fig, (ax0, ax1) = plt.subplots(2, 1, height_ratios=[2, 1], sharex=True, figsize=(10, 2))

# Plot dummy data
ax0.plot(x, y1, label='2025')
ax0.plot(x, y2, label='2026')

ax0.legend()
ax0.axis('off')

# Create table
tab = ax1.table(
    cellText=[
        cellvalue1,
        adjust_right(cellvalue2)
    ],
    rowLabels=["2025", "2026"],
    loc='center',
)
ax1.axis('off')

# Save as .svg
fig.savefig('./table.svg', transparent=True)

# Display on screen
fig.show()

这会让代码更易读,不过和你的实现并不完全相同。

站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章