Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example of a correlation map #1945

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions altair/examples/correlation_matrix.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""
Correlation matrix
--------------
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's important that the length of the underline matches the length of the title when the docs are compiled in Sphinx. You just need to add a few more dashes.

This example shows how to create a correlation matrix and a heatmap from the iris dataset.
"""
# category: other charts
# Load packages

import altair as alt
from vega_datasets import data

# Load the data
df_iris = data.iris()

# Create a correlation matrix
corrMatrix_line = df_iris.corr().round(2).reset_index().rename(columns = {'index':'Var1'}).melt(id_vars = ['Var1'],
value_name = 'Correlation',
var_name = 'Var2')
# Create the heatmap first
heatmap = alt.Chart(corrMatrix_line).encode(
alt.Y('Var1:N', title = ''),
alt.X('Var2:N', title = '', axis=alt.Axis(labelAngle=20))
).mark_rect().encode(
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would move mark_rect() to directly after alt.Chart() and only have a single call to encode() like many of the other examples.

alt.Color('Correlation:Q',
scale=alt.Scale(scheme='viridis'))
)

# Add the correlation values as a text mark
text = heatmap.mark_text(baseline='middle', fontSize=20).encode(
text=alt.Text('Correlation:Q', format='.2'),
color=alt.condition(
alt.datum.Correlation >= 0.95,
alt.value('black'),
alt.value('white')
)
)

# Set the height, width, title and other properties
corrMatrix_chart = (heatmap + text).properties(
width = 400,
height = 400,
title = "Iris variables correlation matrix",
)
corrMatrix_chart.configure_axis(
labelFontSize=18,
titleFontSize=24,
).configure_title(
fontSize=24,
anchor='start',
).configure_legend(
labelFontSize=20,
titleFontSize=20)