我有以下内容合成的数据框,包括数值 and 绝对的列以及label
柱子。
我想绘制一个对角相关矩阵并在上部显示相关系数,如下所示:
预期产出:
尽管合成数据集/数据帧中的分类列df
需要转换成数值,到目前为止我已经用过这个海伯恩的例子 using 'titanic'
数据集是合成的并且适合我的任务,但我添加了label
栏目如下:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="white")
# Generate a large random dataset with synthetic nature (categorical + numerical)
data = sns.load_dataset("titanic")
df = pd.DataFrame(data=data)
# Generate label column randomly '0' or '1'
df['label'] = np.random.randint(0,2, size=len(df))
# Compute the correlation matrix
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(11, 9))
# Generate a custom diverging colormap
cmap = sns.diverging_palette(230, 20, as_cmap=True)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr, mask=mask, cmap=cmap, vmin=-1.0, vmax=1.0, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
我查了相关的post但无法弄清楚如何完成这项任务。到目前为止我能找到的最好的就是这个解决方法可以使用此软件包安装它,它给我以下输出:
#!pip install heatmapz
# Import the two methods from heatmap library
from heatmap import heatmap, corrplot
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="white")
# Generate a large random dataset
data = sns.load_dataset("titanic")
df = pd.DataFrame(data=data)
# Generate label column randomly '0' or '1'
df['label'] = np.random.randint(0,2, size=len(df))
# Compute the correlation matrix
corr = df.corr()
# Generate a mask for the upper triangle
mask = np.triu(np.ones_like(corr, dtype=bool))
mask[np.diag_indices_from(mask)] = False
np.fill_diagonal(mask, True)
# Set up the matplotlib figure
plt.figure(figsize=(8, 8))
# Draw the heatmap using "Heatmapz" package
corrplot(corr[mask], size_scale=300)
Sadly, corr[mask]
不会遮盖此包中的上三角形。
我还注意到,在 R 中,达到这个奇特的情节要容易得多,所以如果有更直接的方法,我很乐意将 Python Pandas 数据帧转换为 R 数据帧因为似乎有一个包,所谓的rpy2
即使在 Google Colab 笔记本中,我们也可以一起使用 Python 和 R:Ref.1
from rpy2.robjects import pandas2ri
pandas2ri.activate()
所以如果是这样的话,我发现这个post1 & post2使用 R 来实现相关矩阵的可视化。
所以,简而言之,我的首要任务是使用 Python 及其包Matplotlib
, seaborn
, Plotly Express
,然后 R 及其包达到预期输出。
Note
我在谷歌给你提供了可执行代码带 R 的 Colab 笔记本 using dataset这样您就可以形成/测试您的最终答案(如果您的解决方案是)rpy2
否则我会对 Pythonic 解决方案感兴趣。