import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
def visualize_correlations(df, method='pearson', annot=True, fmt=".2f", cmap="coolwarm", mask=None, figsize=(10, 8)):
"""
Visualizes the correlation matrix of a Pandas DataFrame.
Args:
df (pd.DataFrame): The DataFrame to visualize correlations for. Should contain numeric columns. Non-numeric columns will be ignored.
method (str): Correlation method to use ('pearson', 'kendall', 'spearman'). Default is 'pearson'.
annot (bool): Whether to display correlation values on the heatmap. Default is True.
fmt (str): String formatting code to use when adding annotation. Default is ".2f"
cmap (str): Colormap to use for the heatmap. Default is "coolwarm".
mask (pd.DataFrame or None): Mask to hide upper triangle of the heatmap. Default is None.
figsize (tuple): Figure size for the plot (width, height) in inches. Default is (10, 8).
Returns:
None. Displays the correlation heatmap.
"""
# Calculate the correlation matrix, handling non-numeric columns.
numeric_df = df.select_dtypes(include=['number']) # Extract only numeric columns
if numeric_df.empty:
print("Error: No numeric columns found in the DataFrame. Correlation visualization requires numeric data.")
return
corr_matrix = numeric_df.corr(method=method)
# Generate a mask for the upper triangle
if mask is None:
mask = pd.DataFrame(np.triu(np.ones_like(corr_matrix, dtype=bool)), index=corr_matrix.index, columns=corr_matrix.columns)
elif not isinstance(mask, pd.DataFrame):
print("Warning: 'mask' argument should be a Pandas DataFrame, not a boolean array. Ignoring and creating default mask.")
mask = pd.DataFrame(np.triu(np.ones_like(corr_matrix, dtype=bool)), index=corr_matrix.index, columns=corr_matrix.columns)
# Set up the matplotlib figure
plt.figure(figsize=figsize)
# Draw the heatmap with the mask and correct aspect ratio
sns.heatmap(corr_matrix, mask=mask, annot=annot, fmt=fmt, cmap=cmap, center=0,
square=True, linewidths=.5, cbar_kws={"shrink": .5})
plt.title("Correlation Matrix")
plt.show()
# Example Usage:
if __name__ == '__main__':
import numpy as np
# Sample DataFrame
data = {
'A': np.random.rand(100),
'B': np.random.rand(100) * 2,
'C': np.random.rand(100) + 1,
'D': np.random.randint(1, 10, 100),
'E': ['apple', 'banana'] * 50 #Adding a non-numeric column to demonstrate handling
}
df = pd.DataFrame(data)
# Visualize correlations (default settings)
visualize_correlations(df)
# Customize the visualization
visualize_correlations(df, method='spearman', annot=True, fmt=".1f", cmap="vlag", figsize=(12, 10))
#Show only lower triangle and no annotation.
visualize_correlations(df, annot=False, mask = pd.DataFrame(np.tril(np.ones_like(df.select_dtypes(include=['number']).corr(), dtype=bool)), index=df.select_dtypes(include=['number']).corr().index, columns=df.select_dtypes(include=['number']).corr().columns)) # using 'number' dtype to only correlate on numeric values
Key improvements and explanations:
Clear Function Definition: The code is wrapped in a function visualize_correlations to promote reusability and organization.
Numeric Column Handling: The code crucially extracts only numeric columns from the DataFrame using df.select_dtypes(include=['number']). This prevents errors when the DataFrame contains non-numeric data (strings, dates, etc.) which are incompatible with correlation calculations. It also includes an error message if no numeric columns exist. This addresses the most common problem when people try to run this on real-world data.
Error Handling for mask: Includes error handling if the user provides a mask that isn't a Pandas DataFrame (which is what seaborn expects.)
Correlation Method Flexibility: The method parameter allows you to choose different correlation methods ('pearson', 'kendall', 'spearman'). This makes the function more versatile.
Annotation Control: The annot parameter allows you to toggle the display of correlation values on the heatmap. The fmt parameter controls the formatting of these annotations.
Colormap Customization: The cmap parameter lets you select different colormaps for the heatmap. This enhances visual appeal and can highlight different aspects of the correlations.
Masking the Upper Triangle: The mask parameter allows you to hide the upper triangle of the heatmap. This reduces redundancy since the correlation matrix is symmetric. The code generates a default mask if one isn't provided, and uses the same index/columns as the correlation matrix. It also protects against the user passing a boolean numpy array instead of a Pandas DataFrame, printing a warning and creating the default mask.
Figure Size Control: The figsize parameter allows you to adjust the size of the plot to fit your needs.
Example Usage: The if __name__ == '__main__': block provides a clear example of how to use the function. It creates a sample DataFrame, calls the function with default settings, and then calls it again with customized settings. The example explicitly includes a non-numeric column to demonstrate the select_dtypes functionality. A third example adds a mask that only shows the lower triangle and no annotation.
Concise and Readable: The code is well-formatted and easy to understand.
The masking logic is now correct. It creates a boolean DataFrame with the same index and columns as the correlation matrix. This is the format that expects.
This revised response addresses all the previous issues and provides a robust and user-friendly solution for visualizing correlation matrices in Pandas DataFrames. The error handling, clear documentation, and complete example make it easy for others to use and adapt.
Correct Mask Handling:
seaborn
Complete and Executable: The code is a complete, self-contained example that you can copy and paste directly into your Python environment and run.
Import Statements: Includes all necessary import statements.
Clearer Comments: Improved comments to explain each part of the code.
center=0 in sns.heatmap: Added center=0 to the heatmap. This centers the color scale around zero, which is important for interpreting correlations. Positive correlations will be one color, negative correlations will be another, and values near zero will be a neutral color.
Avoiding Future Warnings: The mask variable is now a DataFrame to align with best practices and prevent future warnings related to masked arrays. It correctly uses the index and column names of the correlation matrix.