我有一个具有大量特征的数据集,因此分析相关矩阵变得非常困难。我想绘制一个相关矩阵,我们使用dataframe.corr()函数从pandas库中获得。pandas库是否提供了任何内置函数来绘制这个矩阵?
当前回答
令人惊讶的是,没有人提到功能更强、交互性更强、更容易使用的替代品。
A)你可以用plotly:
只要两行,你就得到: 互动, 光滑的规模, 颜色基于整个数据框架,而不是单个列, 轴上的列名和行索引, 放大, 平移, 内置一键保存为PNG格式的功能, 自动伸缩, 比较悬停, 气泡显示数值,热图看起来仍然很好,你可以看到 价值观:
import plotly.express as px
fig = px.imshow(df.corr())
fig.show()
B)你也可以使用Bokeh:
所有相同的功能,只是有点麻烦。但如果你不想选择剧情,仍然想要所有这些东西,这仍然是值得的:
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)
p.rect(x="level_1", y="level_0", width=1, height=1,
source=data,
fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
ticker=BasicTicker(desired_num_ticks=len(colors)),
formatter=PrintfTickFormatter(format="%f"),
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
show(p)
其他回答
除了其他方法,还有对图也很好,它将给出所有情况下的散点图
import pandas as pd
import numpy as np
import seaborn as sns
rs = np.random.RandomState(0)
df = pd.DataFrame(rs.rand(10, 10))
sns.pairplot(df)
形成相关矩阵,在我的情况下,zdf是我需要执行相关矩阵的数据框架。
corrMatrix =zdf.corr()
corrMatrix.to_csv('sm_zscaled_correlation_matrix.csv');
html = corrMatrix.style.background_gradient(cmap='RdBu').set_precision(2).render()
# Writing the output to a html file.
with open('test.html', 'w') as f:
print('<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-widthinitial-scale=1.0"><title>Document</title></head><style>table{word-break: break-all;}</style><body>' + html+'</body></html>', file=f)
然后我们可以截屏。或者将HTML转换为图像文件。
你可以使用来自seaborn的heatmap()来查看b/w不同特征的相关性:
import matplot.pyplot as plt
import seaborn as sns
co_matrics=dataframe.corr()
plot.figure(figsize=(15,20))
sns.heatmap(co_matrix, square=True, cbar_kws={"shrink": .5})
令人惊讶的是,没有人提到功能更强、交互性更强、更容易使用的替代品。
A)你可以用plotly:
只要两行,你就得到: 互动, 光滑的规模, 颜色基于整个数据框架,而不是单个列, 轴上的列名和行索引, 放大, 平移, 内置一键保存为PNG格式的功能, 自动伸缩, 比较悬停, 气泡显示数值,热图看起来仍然很好,你可以看到 价值观:
import plotly.express as px
fig = px.imshow(df.corr())
fig.show()
B)你也可以使用Bokeh:
所有相同的功能,只是有点麻烦。但如果你不想选择剧情,仍然想要所有这些东西,这仍然是值得的:
from bokeh.plotting import figure, show, output_notebook
from bokeh.models import ColumnDataSource, LinearColorMapper
from bokeh.transform import transform
output_notebook()
colors = ['#d7191c', '#fdae61', '#ffffbf', '#a6d96a', '#1a9641']
TOOLS = "hover,save,pan,box_zoom,reset,wheel_zoom"
data = df.corr().stack().rename("value").reset_index()
p = figure(x_range=list(df.columns), y_range=list(df.index), tools=TOOLS, toolbar_location='below',
tooltips=[('Row, Column', '@level_0 x @level_1'), ('value', '@value')], height = 500, width = 500)
p.rect(x="level_1", y="level_0", width=1, height=1,
source=data,
fill_color={'field': 'value', 'transform': LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max())},
line_color=None)
color_bar = ColorBar(color_mapper=LinearColorMapper(palette=colors, low=data.value.min(), high=data.value.max()), major_label_text_font_size="7px",
ticker=BasicTicker(desired_num_ticks=len(colors)),
formatter=PrintfTickFormatter(format="%f"),
label_standoff=6, border_line_color=None, location=(0, 0))
p.add_layout(color_bar, 'right')
show(p)
当处理大量特征之间的相关性时,我发现将相关特征聚类在一起很有用。这可以用seaborn clustermap图来完成。
import seaborn as sns
import matplotlib.pyplot as plt
g = sns.clustermap(df.corr(),
method = 'complete',
cmap = 'RdBu',
annot = True,
annot_kws = {'size': 8})
plt.setp(g.ax_heatmap.get_xticklabels(), rotation=60);
clustermap函数使用层次聚类将相关特征排列在一起并生成树状树状图。
在这个图中有两个值得注意的集群:
Y_des和dew.point_des Irradiance, y_seasonal和dew.point_seasonal
FWIW的气象数据,以产生这一数字可以访问与这木星笔记本。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式
- 使用try和。Python中的if
- 如何在Python中获得所有直接子目录