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:
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/pandas/pandas-create-a-heatmap-using-seaborn-to-visualize-correlations.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics