python - 在 Matplotlib 中并排绘制两个热图
问题描述
我有一个函数可以绘制 DataFrame 的相关矩阵的热图。该函数如下所示:
def corr_heatmap(data):
columns = data.columns
corr_matrix = data.corr()
fig, ax = plt.subplots(figsize=(7, 7))
mat = ax.matshow(corr_matrix, cmap='coolwarm')
ax.set_xticks(range(len(columns)))
ax.set_yticks(range(len(columns)))
ax.set_xticklabels(columns)
ax.set_yticklabels(columns)
plt.setp(ax.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor')
plt.colorbar(mat, fraction=0.045, pad=0.05)
fig.tight_layout()
plt.show()
return mat
当使用 DataFrame 运行时,会输出如下内容:
我想要做的是并排绘制其中两个热图,但我在这样做时遇到了一些麻烦。到目前为止,我所做的是尝试将每个热图分配给 AxesImage 对象并使用子图来绘制它们。
mat1 = corr_heatmap(corr_mat1)
mat2 = corr_heatmap(corr_mat2)
fig = plt.figure(figsize=(15, 15))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax1.plot(ma1)
ax2.plot(ma2)
但这给了我以下错误:
TypeError: float() argument must be a string or a number, not 'AxesImage'
有人会碰巧知道我可以并排绘制两个热图图像的方法吗?谢谢你。
编辑
如果有人想知道我想做的最终代码是什么样的:
def corr_heatmaps(data1, data2, method='pearson'):
# Basic Configuration
fig, axes = plt.subplots(ncols=2, figsize=(12, 12))
ax1, ax2 = axes
corr_matrix1 = data1.corr(method=method)
corr_matrix2 = data2.corr(method=method)
columns1 = corr_matrix1.columns
columns2 = corr_matrix2.columns
# Heat maps.
im1 = ax1.matshow(corr_matrix1, cmap='coolwarm')
im2 = ax2.matshow(corr_matrix2, cmap='coolwarm')
# Formatting for heat map 1.
ax1.set_xticks(range(len(columns1)))
ax1.set_yticks(range(len(columns1)))
ax1.set_xticklabels(columns1)
ax1.set_yticklabels(columns1)
ax1.set_title(data1.name, y=-0.1)
plt.setp(ax1.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor')
plt.colorbar(im1, fraction=0.045, pad=0.05, ax=ax1)
# Formatting for heat map 2.
ax2.set_xticks(range(len(columns2)))
ax2.set_yticks(range(len(columns2)))
ax2.set_xticklabels(columns2)
ax2.set_yticklabels(columns2)
ax2.set_title(data2.name, y=-0.1)
plt.setp(ax2.get_xticklabels(), rotation=45, ha='left', rotation_mode='anchor')
plt.colorbar(im2, fraction=0.045, pad=0.05, ax=ax2)
fig.tight_layout()
这可以(当使用两个 Pandas DataFrame 运行时)沿下图输出一些内容:
解决方案
您需要的是plt.subplots
功能。无需手动将Axes
对象添加到 aFigure
中,您可以初始化 aFigure
和多个Axes
. 然后,它就像调用matshow
each一样简单Axes
:
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
df = pd.DataFrame(np.random.rand(10, 10))
fig, axes = plt.subplots(ncols=2, figsize=(8, 4))
ax1, ax2 = axes
im1 = ax1.matshow(df.corr())
im2 = ax2.matshow(df.corr())
fig.colorbar(im1, ax=ax1)
fig.colorbar(im2, ax=ax2)
您可以稍后执行所有其他格式化。
推荐阅读
- python - 如果在熊猫的给定列中找到字符串匹配,则获取另一列的单元格值
- flutter - 如何通过颤动在屏幕上的某处点击来隐藏覆盖
- java - 使用 setter 方法更新 Room Database 中特定 ID 的特定字段
- installation - 安装程序 EXE 无法启动 - 没有任何错误消息
- linux - 如何使用 Bash 在电子邮件的消息正文中插入新行?
- reactjs - Docker compose:react app 和 nginx 之间共享静态卷
- go - 在数据库中编组 JSON 字段以使用 Pop 进行结构
- python - 获取 AttributeError:模块“aws_cdk.aws_cognito”没有属性“UserPoolResourceServer”错误
- string - 删除包含特定字符串的重复快捷方式
- visual-foxpro - 如何将列表框项目与foxpro中表格中的备注字段进行比较以获得完全匹配?