5 Best Ways to Use Seaborn Library to Display Data Without Background Axis Spines in Python

Rate this post

πŸ’‘ Problem Formulation: When visualizing data, the clarity and aesthetics of the plot can be significantly enhanced by removing unnecessary elements. In many cases, the background axis spines in a Python Seaborn plot may detract from the data presentation. This article provides a guide on how to use the Seaborn library to display data without these background axis spines, with practical examples for each method, detailing the input code and the resulting cleaned-up visual output.

Method 1: Use Seaborn’s Despine Function

Seaborn’s despine() function is designed to remove the top and right spines from the plot. This function also allows for additional customization to remove the left and bottom spines by setting the left and bottom parameters to True. It is a quick and effective way to enhance the visual appeal of a plot.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Sample Seaborn plot
sns.set_theme(style="whitegrid")
iris = sns.load_dataset('iris')
sns.boxplot(x='species', y='sepal_width', data=iris)
sns.despine()

plt.show()

The output is a boxplot with the top and right spines removed, providing a cleaner visual appearance.

This code snippet first sets up a theme with sns.set_theme(), loads the iris dataset, and creates a boxplot using sns.boxplot(). The key function here is sns.despine(), which removes the specified spines and enhances the plot aesthetics. Finally, plt.show() displays the plot.

Method 2: Use Axes Object

You can also interact directly with the axes object in Matplotlib to remove the spines. This method requires manipulation of the Seaborn plot through Matplotlib’s axes object, which offers granular control over the appearance of the plot, allowing you to remove any spine by setting its set_visible() method to False.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Sample Seaborn plot with axes object
sns.set_theme(style="white")
data = sns.load_dataset("tips")
ax = sns.scatterplot(x="total_bill", y="tip", data=data)

# Hide specific spines
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

plt.show()

The output is a scatter plot where only the left and bottom spines are visible, creating a ‘floating’ data presentation.

In this example, after creating a scatterplot with the sns.scatterplot() function, we obtain the axes object and modify its spines. By accessing ax.spines and setting the visibility of ‘top’ and ‘right’ spines to False, the unwanted spines are removed. The final call to plt.show() renders the updated plot.

Method 3: Seaborn Styling Before Plotting

Seaborn provides pre-plot styling options, including the ability to modify the visibility of spines using the axes_style() function. By setting the spines.bottom and spines.left properties within the axes_style() function, you can achieve a spineless plot aesthetic upfront.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Styling before plotting
with sns.axes_style('white', rc={"axes.spines.right": False, "axes.spines.top": False}):
    sns.set_theme()
    data = sns.load_dataset('titanic')
    ax = sns.countplot(x='class', hue='survived', data=data)
    plt.show()

The output is a count plot tailored to exclude the top and right spines initially.

This code modifies the plot’s aesthetics contextually within the with statement. Within this context, Seaborn’s styling is updated to remove the top and right spines, and then the plot is created normally. After ending the with statement, the plot is displayed without the unnecessary spines, allowing for a focused data representation.

Method 4: Modify Seaborn Theme Configuration

The seaborn library offers a set of theme settings that can be customized globally using the set() function. By configuring the despine parameter within the set() function, you can control the visibility of the spines for all subsequent plots within the session.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# Modify Seaborn theme for all plots
sns.set(style="white", despine={'left': True, 'bottom': True})
data = sns.load_dataset("mpg")
sns.lineplot(x="horsepower", y="mpg", data=data)

plt.show()

The output is a line plot without the left and bottom spines, creating a minimalistic and modern appearance.

This method proactively updates the theme settings so that all plots created afterwards will not display the specified spines. The sns.set() command is key here, as it changes the default Seaborn plot configuration for the current session. The despine argument is used to specify which spines to remove globally.

Bonus One-Liner Method 5: Despine in Plot Call

A concise way to remove the spines is to use a one-liner that combines plot creation and spine removal in a single chain of commands.

Here’s an example:

import seaborn as sns
import matplotlib.pyplot as plt

# One-liner for plotting and despine
sns.boxplot(x='day', y='total_bill', data=sns.load_dataset("tips")).spines[['top', 'right']].set_visible(False)
plt.show()

This produces a box plot where the top and right spines have been removed, achieved in a single line.

In this compact example, the plot is created using sns.boxplot(), and immediately afterwards, the spines are accessed and set to not visible. This method is both swift and straightforward, useful for quick modifications without compromising on conciseness.

Summary/Discussion

  • Method 1: Seaborn’s Despine Function. Simple and direct approach suitable for quick modifications. May be limited if global changes for the entire session are required.
  • Method 2: Use Axes Object. Provides detailed control and is well-suited for complex adjustments or customizations. However, it requires knowledge of Matplotlib’s API.
  • Method 3: Seaborn Styling Before Plotting. Good for context-specific styling. Might be less convenient for plots that require variable spine configurations within the same session.
  • Method 4: Modify Seaborn Theme Configuration. Affects all subsequent plots in a session. Ideal for creating a consistent style across multiple plots, but less flexible for on-the-fly changes.
  • Bonus Method 5: Despine in Plot Call. Extremely concise, perfect for quick one-off plots. The clarity of code might suffer in complex plotting scenarios.