Horje
Changing Plot Colors in Seaborn : A Comprehensive Guide

Seaborn is a powerful Python library for data visualization built on top of Matplotlib. It provides a high-level interface for drawing attractive and informative statistical graphics. One of the key features of Seaborn is its ability to handle color palettes effectively, which can significantly enhance the readability and aesthetics of your plots. This article will guide you through various methods to change plot colors in Seaborn, focusing on different types of plots and color customization techniques.

Introduction to Seaborn Color Customization

Seaborn offers several ways to customize plot colors, including changing the palette, specifying individual colors, and using built-in themes. These customizations can enhance the clarity and aesthetics of your visualizations, making them more effective in communicating your data.

Seaborn offers several built-in color palettes and allows for extensive customization. The primary methods to change colors in Seaborn plots include using the color parameter for single colors and the palette parameter for multiple colors. Understanding these options is crucial for creating visually appealing and informative plots.

Changing the Color Palette In Seaborn

Seaborn provides a range of built-in color palettes that you can use to style your plots. You can set a color palette using the set_palette() function.

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
tips = sns.load_dataset('tips')

# Set a color palette
sns.set_palette("husl")

# Create a boxplot with the new color palette
sns.boxplot(x='day', y='total_bill', data=tips)
plt.show()

Output:

download---2024-07-11T104406767

Changing the Color Palette

In this example, the “husl” palette is applied to the boxplot. Seaborn supports several other palettes, including “deep”, “muted”, “bright”, “dark”, and more.

Customizing Colors for Specific Plots

You can also specify colors for individual plots directly using the color parameter or by setting the palette parameter for specific plots.

1. Changing Color for a Single Plot

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
tips = sns.load_dataset('tips')

# Create a boxplot with a specific color
sns.boxplot(x='day', y='total_bill', data=tips, color='skyblue')
plt.show()

Output:

download---2024-07-11T104530480

Changing Color for a Single Plot

2. Using Palette for Categorical Plots

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
tips = sns.load_dataset('tips')

# Create a boxplot with a custom palette
sns.boxplot(x='day', y='total_bill', data=tips, palette='Set2')
plt.show()

Output:

download---2024-07-11T104619173

Using Palette for Categorical Plots

3. Changing the Color of a Single Line

To change the color of a single line in a Seaborn plot, you can use the color parameter within the lineplot() function. This parameter accepts various color formats, including named colors, hex codes, and RGB tuples.

Python
import seaborn as sns
import pandas as pd

# Create a sample DataFrame
df = pd.DataFrame({
    'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    'sales': [3, 3, 5, 4, 5, 6, 8, 9, 14, 18]
})

# Create a line plot with a specific color
sns.lineplot(data=df, x='day', y='sales', color='red')

Output:

download---2024-07-11T104729280

Changing the Color of a Single Line

In this example, the line color is set to red using the color='red' argument. You can also use hex color codes:

4. Changing the Color of Multiple Lines

When plotting multiple lines, you can use the palette parameter to specify a range of colors. This is particularly useful when you want to distinguish between different categories in your data.

Python
df = pd.DataFrame({
    'day': [1, 2, 3, 4, 5, 1, 2, 3, 4, 5],
    'store': ['A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B'],
    'sales': [3, 3, 5, 4, 7, 6, 8, 9, 12, 13]
})

# Create a line plot with the mako_r color palette
palette = sns.color_palette("mako_r", 2)
sns.lineplot(data=df, x='day', y='sales', hue='store', palette=palette, linewidth=2.5, style='store', markers=True)

# Customizing the plot further
plt.title('Sales Trends by Store', fontsize=16)
plt.xlabel('Day', fontsize=14)
plt.ylabel('Sales', fontsize=14)
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.grid(True, linestyle='--', alpha=0.7)
plt.legend(title='Store', title_fontsize='13', loc='upper left')
plt.show()

Output:

download---2024-07-11T104951537

Changing the Color of Multiple Lines

Customizing Colors with Hex Codes or RGB Values

You can also create custom color palettes by passing a list of colors in any valid Matplotlib format, including RGB tuples, hex color codes, or HTML color names.

You can define custom colors using hex codes or RGB values for precise control over your plot’s appearance.

Example:

custom_palette = ["#090364", "#091e75", "#093885", "#085396", "#086da6",
"#0888b7", "#08a2c7", "#07bdd8", "#07d7e8", "#07f2f9",
"#f9ac07", "#c77406", "#963b04", "#640303"]

sns.set_palette(custom_palette)
sns.scatterplot(x='length', y='type', hue='temperature', data=df)

1. Using Hex Codes

The code loads the ‘tips’ dataset and uses Seaborn to create a boxplot of ‘total_bill’ across ‘day’, applying a custom color palette defined by specific hex color codes. The plot is then displayed using Matplotlib.

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
tips = sns.load_dataset('tips')

# Define a custom color palette using hex codes
custom_palette = ['#FF6347', '#4682B4', '#8A2BE2', '#FFD700']

# Create a boxplot with the custom color palette
sns.boxplot(x='day', y='total_bill', data=tips, palette=custom_palette)
plt.show()

Output:

Screenshot-2024-07-03-004704

Using Hex Codes

2. Using RGB Values

The code loads the ‘tips’ dataset and creates a boxplot of ‘total_bill’ across ‘day’ using Seaborn, with a custom color palette defined by specific RGB values. The plot is then displayed using Matplotlib.

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
tips = sns.load_dataset('tips')

# Define a custom color palette using RGB values
custom_palette = [(0.2, 0.4, 0.6), (0.4, 0.6, 0.8), (0.6, 0.8, 1.0), (0.8, 1.0, 0.6)]

# Create a boxplot with the custom color palette
sns.boxplot(x='day', y='total_bill', data=tips, palette=custom_palette)
plt.show()

Output:

Screenshot-2024-07-03-004754

Using RGB Values

Changing Colors in Specific Plot Types

Different plot types in Seaborn have specific parameters for color customization. Here are a few examples:

1. Scatter Plot

Python
import seaborn as sns
import matplotlib.pyplot as plt

# Sample data
iris = sns.load_dataset('iris')

# Create a scatter plot with custom colors
sns.scatterplot(x='sepal_length', y='sepal_width', data=iris, hue='species', palette='viridis')
plt.show()

Output:

Screenshot-2024-07-03-004841

Scatter Plot

2. Heatmap

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

# Sample data
data = np.random.rand(10, 12)

# Create a heatmap with a custom colormap
sns.heatmap(data, cmap='coolwarm')
plt.show()

Output:

Screenshot-2024-07-03-004925

Heatmap

Conclusion

Changing plot colors in Seaborn is a versatile way to enhance the visual appeal and readability of your visualizations. Whether you’re using built-in palettes, custom colors, or adjusting specific plot types, Seaborn provides a straightforward and flexible approach to color customization. By following the methods outlined in this article, you can create visually striking plots that effectively communicate your data insights.




Reffered: https://www.geeksforgeeks.org


AI ML DS

Related
Adding Titles to Seaborn Heatmaps: A Comprehensive Guide Adding Titles to Seaborn Heatmaps: A Comprehensive Guide
What is YFinance library? What is YFinance library?
How to choose Batch Size and Number of Epochs When Fitting a Model? How to choose Batch Size and Number of Epochs When Fitting a Model?
Image Segmentation Using Mean Shift Clustering Image Segmentation Using Mean Shift Clustering
Human Resource Management Analytics Dashboard in R Human Resource Management Analytics Dashboard in R

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
17