
本教程详细介绍了在无法控制原始绘图函数输出单个matplotlib figure 对象时,如何将这些独立的图表内容整合到一个新的、统一的图表中。核心方法是提取每个原始图表中的数据,然后在新创建的子图中重新绘制这些数据,最终生成一个结构清晰、内容丰富的组合图表。
在数据可视化过程中,我们经常会遇到需要整合多个独立生成的Matplotlib图表(matplotlib.figure.Figure 对象)到一个单一的综合图表中的场景。例如,当现有函数返回完整的Figure对象,而我们希望将这些独立的图表作为子图排列在一个新的布局中时。由于Matplotlib的Figure对象通常是独立的画布,直接将其“嵌入”为另一个Figure的子图并不直接。本教程将介绍一种通用的解决方案:通过提取原始图表中的数据,然后在新的主图表中重新绘制这些数据。
当函数返回Figure对象时,我们失去了对该图表内部Axes对象的直接控制,无法简单地将它们传递给plt.subplots()。在这种情况下,最可靠的方法是:
为了演示,我们首先创建两个模拟函数,它们各自生成并返回一个matplotlib.figure.Figure对象。
import matplotlib.pyplot as plt
import numpy as np
def generate_figure_1():
"""生成第一个图表,包含一条正弦曲线。"""
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
x = np.linspace(0, 2 * np.pi, 100)
y = np.sin(x)
ax.plot(x, y, label='Sin(x)', color='blue')
ax.set_title('Figure 1: Sine Wave')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.legend()
plt.close(fig) # 关闭当前Figure,避免在notebook中显示
return fig
def generate_figure_2():
"""生成第二个图表,包含一条余弦曲线和一个散点图。"""
fig = plt.figure(figsize=(6, 4))
ax1 = fig.add_subplot(211) # 第一个子图
ax2 = fig.add_subplot(212) # 第二个子图
x = np.linspace(0, 2 * np.pi, 100)
y_cos = np.cos(x)
ax1.plot(x, y_cos, label='Cos(x)', color='red')
ax1.set_title('Figure 2, Subplot 1: Cosine Wave')
ax1.legend()
x_scatter = np.random.rand(50) * 10
y_scatter = np.random.rand(50) * 10
ax2.scatter(x_scatter, y_scatter, label='Random Scatter', color='green', marker='o')
ax2.set_title('Figure 2, Subplot 2: Scatter Plot')
ax2.legend()
fig.tight_layout()
plt.close(fig) # 关闭当前Figure
return fig
# 生成两个独立的Figure对象
fig_a = generate_figure_1()
fig_b = generate_figure_2()接下来,我们将从fig_a和fig_b中提取绘制数据。这涉及到访问Figure对象的axes属性,然后遍历每个Axes对象中的线条、散点等元素。
def extract_plot_data(figure):
"""从给定的Figure对象中提取所有Axes及其上的绘制数据。"""
extracted_data = []
for ax in figure.axes:
ax_data = {'lines': [], 'scatter': [], 'bars': [], 'title': ax.get_title(), 'xlabel': ax.get_xlabel(), 'ylabel': ax.get_ylabel(), 'legend_handles_labels': ([], [])}
# 提取线条数据
for line in ax.lines:
ax_data['lines'].append({
'xdata': line.get_xdata(),
'ydata': line.get_ydata(),
'color': line.get_color(),
'linestyle': line.get_linestyle(),
'marker': line.get_marker(),
'label': line.get_label()
})
# 提取散点数据 (通常是PathCollection)
for collection in ax.collections:
if isinstance(collection, plt.cm.ScalarMappable): # 排除colorbar等
continue
if hasattr(collection, 'get_offsets') and hasattr(collection, 'get_facecolors'):
# 简单处理散点图,可能需要更复杂的逻辑处理颜色映射等
offsets = collection.get_offsets()
ax_data['scatter'].append({
'xdata': offsets[:, 0],
'ydata': offsets[:, 1],
'color': collection.get_facecolors()[0] if collection.get_facecolors().size > 0 else 'black',
'marker': collection.get_paths()[0].vertices[0] if collection.get_paths() else 'o', # 尝试获取marker
'label': collection.get_label()
})
# 提取柱状图数据 (通常是Rectangle对象)
for container in ax.containers:
if isinstance(container, plt.BarContainer):
for bar in container.patches:
ax_data['bars'].append({
'x': bar.get_x(),
'y': bar.get_height(),
'width': bar.get_width(),
'color': bar.get_facecolor(),
'label': container.get_label() # BarContainer的label
})
# 提取图例信息
if ax.get_legend() is not None:
handles, labels = ax.get_legend_handles_labels()
ax_data['legend_handles_labels'] = (handles, labels)
extracted_data.append(ax_data)
return extracted_data
# 提取数据
data_from_fig_a = extract_plot_data(fig_a)
data_from_fig_b = extract_plot_data(fig_b)
all_extracted_data = data_from_fig_a + data_from_fig_b注意事项:
现在,我们将创建一个新的Figure对象,并根据需要创建子图布局,然后将提取的数据绘制到这些新的子图中。
# 计算总共需要多少个子图
num_subplots = len(all_extracted_data)
# 确定子图布局 (例如,两列布局)
rows = int(np.ceil(num_subplots / 2))
cols = 2 if num_subplots > 1 else 1
# 创建新的主图表和子图
new_fig, new_axes = plt.subplots(rows, cols, figsize=(cols * 7, rows * 5))
new_axes = new_axes.flatten() # 将axes数组展平,方便迭代
# 遍历所有提取的数据,并在新的子图中重新绘制
for i, ax_data in enumerate(all_extracted_data):
current_ax = new_axes[i]
# 重新绘制线条
for line_info in ax_data['lines']:
current_ax.plot(line_info['xdata'], line_info['ydata'],
color=line_info['color'],
linestyle=line_info['linestyle'],
marker=line_info['marker'],
label=line_info['label'])
# 重新绘制散点
for scatter_info in ax_data['scatter']:
current_ax.scatter(scatter_info['xdata'], scatter_info['ydata'],
color=scatter_info['color'],
marker=scatter_info['marker'],
label=scatter_info['label'])
# 重新绘制柱状图 (这里只是一个简单示例,可能需要更多参数)
for bar_info in ax_data['bars']:
current_ax.bar(bar_info['x'], bar_info['y'],
width=bar_info['width'],
color=bar_info['color'],
label=bar_info['label'])
# 设置标题和轴标签
current_ax.set_title(ax_data['title'])
current_ax.set_xlabel(ax_data['xlabel'])
current_ax.set_ylabel(ax_data['ylabel'])
# 添加图例
if ax_data['legend_handles_labels'][1]: # 如果有标签
current_ax.legend()
# 调整布局,确保所有元素可见
new_fig.tight_layout()
# 显示最终合并的图表
plt.show()最后,我们可以使用plt.savefig()函数将合并后的图表保存到文件中。
# 保存合并后的图表
plt.savefig("combined_matplotlib_figures.png", dpi=300, bbox_inches='tight')
print("合并图表已保存为 combined_matplotlib_figures.png")通过上述步骤,即使面对无法直接控制的Figure对象,我们也能够有效地提取其核心可视化数据,并在一个统一的Matplotlib图表中进行重新组织和展示,从而实现多个图表的合并。
以上就是如何将多个Matplotlib图表合并为一个综合图表的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号