0Pricing
Pandas & NumPy Academy · Aula

Mapas de calor para matrizes de correlação

Calcule uma matriz de correlação com DataFrame.corr() e visualize-a como um mapa de calor codificado por cores com sns.heatmap.

Mapas de calor para matrizes de correlação é uma aula grátis de Pandas & NumPy Academy no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Pandas & NumPy Academy, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Pandas & NumPy Academy inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

What Is a Correlation Matrix?

A correlation matrix is a square table where entry (i, j) contains the Pearson correlation coefficient between column i and column j. Values range from -1 (perfect negative linear correlation) to +1 (perfect positive), with 0 meaning no linear relationship. The diagonal is always 1 (a variable is perfectly correlated with itself). Correlation matrices are the first step in understanding which variables move together before building a model.

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# Compute correlation matrix for numeric columns
tips = sns.load_dataset('tips')
corr = tips[['total_bill', 'tip', 'size']].corr()
print(corr.round(2))

Computing the Correlation Matrix

Call DataFrame.corr() to compute pairwise Pearson correlations for all numeric columns. The method parameter controls which correlation to compute: 'pearson' (default, linear), 'spearman' (rank-based, robust to outliers and non-linear monotonic relationships), or 'kendall'. For skewed financial or count data, Spearman is often more informative than Pearson.

import pandas as pd
import seaborn as sns

tips = sns.load_dataset('tips')
numeric = tips.select_dtypes(include='number')

# Pearson vs Spearman
pearson = numeric.corr(method='pearson')
spearman = numeric.corr(method='spearman')

print('Pearson:')
print(pearson.round(2))
print('\nSpearman:')
print(spearman.round(2))

Basic Heatmap with sns.heatmap

sns.heatmap(data) takes a 2D array or DataFrame and renders it as a colour grid — each cell's colour encodes its numeric value. When applied to a correlation matrix, warm colours (red) typically represent positive correlation and cool colours (blue) represent negative. The annot=True parameter prints the numeric value inside each cell, which is essential for reading a correlation heatmap accurately.

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()

sns.heatmap(corr, annot=True, fmt='.2f')
plt.title('Correlation Heatmap — Tips Dataset')
plt.tight_layout()
plt.show()

Choosing the Right Colour Map

For correlation matrices, always use a diverging colour map centred at zero: cmap='coolwarm', 'RdBu_r', or 'vlag'. These maps use one colour for positive values, another for negative, and a neutral midpoint at zero. Avoid sequential colour maps (like 'Blues') for correlation data because they make it impossible to distinguish positive from negative correlations visually. Set vmin=-1, vmax=1 to fix the colour scale to the full correlation range.

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()

sns.heatmap(
    corr,
    annot=True,
    fmt='.2f',
    cmap='coolwarm',
    vmin=-1,
    vmax=1,
    center=0
)
plt.title('Correlation Heatmap with Diverging Palette')
plt.tight_layout()
plt.show()

Masking the Upper Triangle

Because a correlation matrix is symmetric (corr[i,j] == corr[j,i]), showing both halves is redundant. Use np.triu to create an upper-triangle mask and pass it to mask= in sns.heatmap. This cuts the number of cells in half, making the plot less cluttered and easier to read. The diagonal values (all 1.0) can also be masked since they carry no information.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()

# Mask the upper triangle (including diagonal)
mask = np.triu(np.ones_like(corr, dtype=bool))

sns.heatmap(
    corr,
    mask=mask,
    annot=True,
    fmt='.2f',
    cmap='coolwarm',
    vmin=-1,
    vmax=1
)
plt.title('Lower-Triangle Correlation Heatmap')
plt.tight_layout()
plt.show()

Customising Annotation and Cell Size

Control the annotation format with fmt= (e.g. '.2f' for two decimal places) and the font size with annot_kws={'size': 10}. The linewidths parameter adds thin lines between cells, making the grid easier to read for large matrices. Use square=True to force square cells regardless of the figure dimensions, which gives heatmaps a clean, balanced appearance.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Load a wider dataset for a more interesting heatmap
penguins = sns.load_dataset('penguins').select_dtypes('number')
corr = penguins.corr()
mask = np.triu(np.ones_like(corr, dtype=bool))

sns.heatmap(
    corr,
    mask=mask,
    annot=True,
    fmt='.2f',
    cmap='vlag',
    vmin=-1,
    vmax=1,
    linewidths=0.5,
    square=True,
    annot_kws={'size': 10}
)
plt.title('Penguins Correlation Matrix')
plt.tight_layout()
plt.show()

Clustering with clustermap

sns.clustermap() reorders rows and columns using hierarchical clustering to group variables with similar correlation patterns together. This makes it much easier to identify blocks of correlated features in large matrices. The dendrogram on the top and left axes shows the clustering tree. Use method='ward' and metric='euclidean' as sensible defaults for correlation-based clustering.

import seaborn as sns
import matplotlib.pyplot as plt

penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()

sns.clustermap(
    corr,
    cmap='coolwarm',
    vmin=-1,
    vmax=1,
    annot=True,
    fmt='.2f',
    figsize=(6, 6)
)
plt.suptitle('Clustered Correlation Matrix', y=1.02)
plt.show()

Heatmap for Pivot Table Data

Heatmaps are not limited to correlation matrices — any 2D numeric table benefits from colour encoding. A common pattern is to compute a pivot table (e.g. average tip by day and time) and then visualise it as a heatmap. This turns a dense table of numbers into an instantly scannable colour grid where the highest and lowest values jump out visually.

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

tips = sns.load_dataset('tips')

# Pivot: average bill by day and time
pivot = tips.pivot_table(
    values='total_bill',
    index='day',
    columns='time',
    aggfunc='mean'
)

sns.heatmap(pivot, annot=True, fmt='.1f', cmap='YlOrRd')
plt.title('Average Bill by Day and Time')
plt.tight_layout()
plt.show()

Interpreting Correlation Values

When interpreting correlations, use these rough benchmarks: |r| < 0.2 = negligible, 0.2-0.4 = weak, 0.4-0.6 = moderate, 0.6-0.8 = strong, > 0.8 = very strong. However, correlation tells you nothing about causation, and can be spurious (coincidentally correlated due to a third confounding variable). Always pair numerical correlation analysis with scatter plots to verify the relationship is actually linear and not driven by outliers.

import pandas as pd
import seaborn as sns

# Find the most correlated pairs
penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()

# Unstack to get pairs, remove self-correlations, sort
pairs = (corr
    .unstack()
    .reset_index()
    .rename(columns={'level_0': 'var1', 'level_1': 'var2', 0: 'r'})
    .query('var1 != var2')
    .assign(abs_r=lambda df: df['r'].abs())
    .sort_values('abs_r', ascending=False)
    .drop_duplicates(subset='abs_r')
)
print(pairs.head(6).to_string(index=False))

Large Dataset Heatmaps: Subsetting

For DataFrames with many columns, a full correlation heatmap becomes unreadable. A better approach is to filter the correlation matrix to show only pairs with |r| above a threshold (e.g. 0.5), or to select only the most-correlated features with a target variable. You can also subset by domain — for example, plotting correlations among financial metrics separately from operational metrics in a business dataset.

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# Show only features with |r| > 0.4 with any other feature
penguins = sns.load_dataset('penguins').select_dtypes('number').dropna()
corr = penguins.corr()

# Filter columns that have at least one high correlation (excluding diagonal)
high_corr = (corr.abs() > 0.4).any(axis=1)
filtered = corr.loc[high_corr, high_corr]
mask = np.triu(np.ones_like(filtered, dtype=bool))

sns.heatmap(filtered, mask=mask, annot=True,
            fmt='.2f', cmap='coolwarm', vmin=-1, vmax=1)
plt.title('High-Correlation Subset')
plt.tight_layout()
plt.show()

Saving Heatmaps to Files

Heatmaps are often included in reports and presentations. Call plt.savefig('filename.png', dpi=150, bbox_inches='tight') after creating the heatmap to save it. The bbox_inches='tight' argument prevents axis labels from being clipped. For PDF reports, use format='pdf'. When using sns.clustermap, the figure is stored in the returned object: g = sns.clustermap(...); g.savefig('plot.png').

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

tips = sns.load_dataset('tips')
corr = tips.select_dtypes('number').corr()
mask = np.triu(np.ones_like(corr, dtype=bool))

fig, ax = plt.subplots(figsize=(6, 5))
sns.heatmap(corr, mask=mask, annot=True, fmt='.2f',
            cmap='coolwarm', vmin=-1, vmax=1,
            linewidths=0.5, ax=ax)
ax.set_title('Correlation Heatmap')

# Save to file
plt.savefig('/tmp/correlation_heatmap.png', dpi=150, bbox_inches='tight')
plt.close()
print('Saved to /tmp/correlation_heatmap.png')

Quick Check

Test your understanding of correlation heatmaps from this lesson.

Lesson Recap

In this lesson you learned: DataFrame.corr() computes pairwise correlations, sns.heatmap renders them as a colour grid with diverging colour maps and annotation, and masking the upper triangle removes redundancy. Next up we explore the full Exploratory Data Analysis pipeline — a systematic checklist for profiling any new dataset.

Perguntas Frequentes

A aula “Mapas de calor para matrizes de correlação” é grátis?

Sim — o texto completo de “Mapas de calor para matrizes de correlação” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Pandas & NumPy Academy, atualize para CoddyKit PRO. O curso de Pandas & NumPy Academy inclui 4 aulas no total.

O que vou aprender em “Mapas de calor para matrizes de correlação”?

Calcule uma matriz de correlação com DataFrame.corr() e visualize-a como um mapa de calor codificado por cores com sns.heatmap. Você pratica Pandas & NumPy Academy com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar Pandas & NumPy Academy?

Nenhuma experiência prévia é necessária. Pandas & NumPy Academy no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Mapas de calor para matrizes de correlação”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de Pandas & NumPy Academy?

Sim. Cada aula de Pandas & NumPy Academy inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Gráficos de distribuição: histplot e kdeplot
  2. Gráficos categóricos: boxplot, barplot e violinplot
  3. Gráficos de dispersão e gráficos de pares
  4. Mapas de calor para matrizes de correlação
← Voltar para Pandas & NumPy Academy