本文目录导读:
下面是一个使用 Matplotlib 和 Pandas 实现 Python 图表导出(保存为图片或 PDF)的完整案例。
基础环境准备
pip install matplotlib pandas numpy
生成示例数据并绘制图表
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# 生成示例数据
np.random.seed(42)
dates = pd.date_range('2024-01-01', periods=30)
values = np.random.randn(30).cumsum() + 100
df = pd.DataFrame({'日期': dates, '数值': values})
# 创建图表
plt.figure(figsize=(10, 6))
plt.plot(df['日期'], df['数值'], marker='o', linestyle='-', color='b', label='时序数据')'示例图表 - 时间序列', fontsize=14)
plt.xlabel('日期')
plt.ylabel('数值')
plt.grid(True, alpha=0.3)
plt.legend()
# 自动调整布局
plt.tight_layout()
导出图表为图片
导出为 PNG(最常用)
# 保存为PNG格式(默认dpi=100)
plt.savefig('chart_output.png', dpi=150, bbox_inches='tight')
print("✅ 已保存为: chart_output.png")
导出为不同格式
# 1. 高清PNG
plt.savefig('chart_hd.png', dpi=300, bbox_inches='tight')
# 2. PDF(矢量图,适合论文)
plt.savefig('chart_output.pdf', bbox_inches='tight')
# 3. SVG(矢量图,适合网页)
plt.savefig('chart_output.svg', bbox_inches='tight')
# 4. JPEG(适合照片类图表)
plt.savefig('chart_output.jpg', dpi=200, bbox_inches='tight', quality=95)
完整可运行案例
import matplotlib.pyplot as plt
import numpy as np
def create_and_export_chart():
"""创建并导出多子图图表"""
# 创建图表(2行2列的子图)
fig, axes = plt.subplots(2, 2, figsize=(12, 10))
x = np.linspace(0, 10, 100)
# 子图1:正弦波
axes[0, 0].plot(x, np.sin(x), 'r-', label='sin(x)')
axes[0, 0].set_title('正弦函数')
axes[0, 0].legend()
axes[0, 0].grid(True)
# 子图2:余弦波
axes[0, 1].plot(x, np.cos(x), 'b-', label='cos(x)')
axes[0, 1].set_title('余弦函数')
axes[0, 1].legend()
axes[0, 1].grid(True)
# 子图3:散点图
np.random.seed(42)
x_scatter = np.random.randn(50)
y_scatter = np.random.randn(50)
axes[1, 0].scatter(x_scatter, y_scatter, c='green', alpha=0.6)
axes[1, 0].set_title('随机散点图')
axes[1, 0].grid(True)
# 子图4:条形图
categories = ['A', 'B', 'C', 'D', 'E']
values = np.random.randint(10, 50, 5)
axes[1, 1].bar(categories, values, color='purple', alpha=0.7)
axes[1, 1].set_title('分类数据条图')
axes[1, 1].grid(True, axis='y')
# 全局设置
plt.suptitle('多子图示例 - 2024', fontsize=16)
plt.tight_layout()
# 导出图表
export_formats(fig)
# 显示图表(可选)
plt.show()
def export_formats(fig):
"""导出多种格式"""
formats = {
'png': {'dpi': 300, 'bbox_inches': 'tight'},
'pdf': {'bbox_inches': 'tight'},
'svg': {'bbox_inches': 'tight'},
'jpg': {'dpi': 200, 'bbox_inches': 'tight', 'quality': 95}
}
for fmt, kwargs in formats.items():
filename = f'chart_export.{fmt}'
fig.savefig(filename, **kwargs)
print(f"✅ 已保存: {filename}")
# 运行
create_and_export_chart()
使用 Pandas 直接导出
import pandas as pd
import matplotlib.pyplot as plt
# 创建DataFrame
df = pd.DataFrame({
'月份': ['1月', '2月', '3月', '4月', '5月'],
'销售额': [120, 150, 180, 160, 200],
'利润': [30, 45, 50, 42, 60]
})
# 直接在DataFrame上绘制
ax = df.plot(x='月份', y=['销售额', '利润'], kind='bar', figsize=(10, 6))'月度销售数据')
plt.ylabel('金额(万元)')
plt.grid(True, alpha=0.3)
# 保存
plt.savefig('sales_data.png', dpi=200, bbox_inches='tight')
print("✅ 销售数据图表已保存")
导出过程中的常用参数说明
plt.savefig(
'exported_chart.png', # 文件名(含路径)
dpi=300, # 分辨率(默认100)
bbox_inches='tight', # 自动裁剪边距
pad_inches=0.1, # 边距大小
transparent=False, # 是否透明背景
facecolor='white', # 背景色
edgecolor='none', # 边框色
format='png', # 强制指定格式
quality=95 # JPEG质量(0-100)
)
批量导出示例
import os
def batch_export_charts():
"""批量生成并导出多种图表"""
output_dir = 'chart_exports'
os.makedirs(output_dir, exist_ok=True)
np.random.seed(42)
data = np.random.randn(100)
chart_configs = [
{'type': 'histogram', 'title': '直方图', 'filename': 'histogram.png'},
{'type': 'boxplot', 'title': '箱线图', 'filename': 'boxplot.png'},
{'type': 'density', 'title': '密度图', 'filename': 'density.png'}
]
for config in chart_configs:
fig, ax = plt.subplots(figsize=(8, 5))
if config['type'] == 'histogram':
ax.hist(data, bins=20, alpha=0.7, color='blue')
elif config['type'] == 'boxplot':
ax.boxplot(data)
elif config['type'] == 'density':
ax.hist(data, bins=50, density=True, alpha=0.6, color='green')
# 添加KDE曲线
from scipy import stats
kde_x = np.linspace(min(data), max(data), 100)
kde = stats.gaussian_kde(data)
ax.plot(kde_x, kde(kde_x), 'r-', lw=2)
ax.set_title(config['title'])
ax.grid(True, alpha=0.3)
# 导出
filepath = os.path.join(output_dir, config['filename'])
fig.savefig(filepath, dpi=200, bbox_inches='tight')
plt.close(fig) # 关闭图节省内存
print(f"✅ 已保存: {filepath}")
# 运行批量导出
batch_export_charts()
常见问题与解决方案
1 中文显示问题
# 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 或 ['Microsoft YaHei'] plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
2 图片过大或过小
fig = plt.figure(figsize=(8, 6)) # 调整尺寸
plt.savefig('output.png', dpi=150) # 调整分辨率
3 保存前预览
plt.show() # 先显示查看
# 确认满意后再保存
plt.savefig('final_chart.png')
这个案例涵盖了 Python 图表导出的主要场景:
- ✅ 基础图表创建与导出
- ✅ 多格式导出(PNG、PDF、SVG、JPG)
- ✅ 多子图导出
- ✅ Pandas 直接导出
- ✅ 批量导出
- ✅ 参数调优
你可以根据实际需求选择合适的方式。最常用的方案是:
plt.savefig('chart.png', dpi=300, bbox_inches='tight') 标签: 图表导出