w3resource

Pandas - Creating a Heatmap Using Seaborn to Visualize Correlations


Pandas: Visualization Integration Exercise-7 with Solution


Write a Pandas program to create a Heatmap Visualization with Seaborn.

This exercise demonstrates how to create a heatmap using Seaborn to visualize a correlation matrix in a DataFrame.

Sample Solution :

Code :

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

# Create a sample DataFrame
df = pd.DataFrame({
    'Math': [90, 85, 80, 75, 70],
    'Science': [85, 80, 75, 70, 65],
    'English': [80, 75, 70, 65, 60]
})

# Compute the correlation matrix
corr_matrix = df.corr()

# Create a heatmap to visualize the correlation matrix
sns.heatmap(corr_matrix, annot=True)

# Add a title
plt.title('Subject Correlation Heatmap')

# Display the plot
plt.show()

Output:

Pandas - Heatmap Visualization with Seaborn

Explanation:

  • Created a DataFrame with grades in different subjects.
  • Calculated the correlation matrix using df.corr().
  • Used sns.heatmap() to plot the correlation matrix, adding annotations to show correlation values.
  • Displayed the heatmap with a title.

Python-Pandas Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.