Author avatar

Vivek Kumar

Controlling Figure Aesthetics

Vivek Kumar

  • Apr 19, 2019
  • 10 Min read
  • 174 Views
  • Apr 19, 2019
  • 10 Min read
  • 174 Views
Data
Seaborn

Introduction

In this guide, you are going to learn about the fundamentals of controlling the Seaborn figure. It is well known that Matplotlib provides an extensive list of modules, methods, and attributes to make a figure more appealing but still lacks high-level methods. On the other hand, Seaborn provides frequently used high-level methods built upon Matplotlib.

By the end of this guide you will be able to implement the following concepts:

  1. Handling Seaborn figure styles
  2. Removing axes spines
  3. Overriding elements of the Seaborn styles

The Baseline

In this guide we are going to use the following libraries:

Syntax

1
2
3
4
5
# Importing necessary libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
python

Handling Seaborn Figure Styles

The impact of colors in a plot plays an important role, like highlighting an insight or diminishing it. Consider a plot created from the given code:

1
2
3
4
5
6
7
8
9
10
11
# Setting a figure and axes
fig, ax = plt.subplots(nrows=1, ncols=1)

# Setting background color to blue
ax.set_facecolor('b')

# Creating a line plot
plt.plot([1, 5, 8, 9, 2], linewidth=3)

# Displaying the result
plt.show()
python

Bk

As you can observe, creating a light blue line over a dark blue background can diminish the effect of the line plot. The effect gets even worse if we choose any other wrong combination with more details on the plot (more lines). Therefore, choosing the right figure style is an utmost necessity.

By default, Seaborn provides five figure styles to highlight the important aspect in a plot. Given below are the five figure styles:

  1. darkgrid
  2. whitegrid
  3. dark
  4. white
  5. ticks

Initial two styles (darkgrid and whitegrid) can be useful in a situation when any quantitative variable is involved. Dark and white can be used to focus on the chart details rather than the grids. The last, ticks, can be used to improvise the structure of the plot.

Let us implement them with an example.

1. Darkgrid and Whitegrid

To understand the relevance of darkgrid and whitegrid, we will use some quantitative data.

First, let we build a box plot using random data and showcase the implementation of darkgrid. The insights from the plot are heavily dependent upon how well the grid is presented.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Setting figure size
plt.figure(figsize=(8, 5))

# Initializing the data
x = np.array([85, 44, 5, 2, 6, 77, 5, 24, 1, 2, 9, 5, 7, 11, 2, 5, 7, 99, 56, 22, 25])
df = pd.DataFrame({'x': x})

# Setting darkgrid figure style
sns.set_style('darkgrid')

# Plotting
sns.boxplot(x='x', data=df, color='g', orient='v')

# Labeling
plt.title('Darkgrid Figure Style', weight='bold', fontsize=18)
plt.xlabel('x', fontsize=14)

# Displaying the plot
plt.show()
python

darkgrid

As you can observe from the figure, grid lines play an important role in having an estimate of each quartile. You can also use whitegrid in place of darkgrid in the above code.

Second, let us build a barplot and observe how whitegrid helps to estimate the height of each bar as shown:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Setting figure size
plt.figure(figsize=(8, 5))

# Initializing the data
x = np.array(['A', 'B', 'C'])
y = np.array([85, 44, 25])
df = pd.DataFrame({'x': x, 'y': y})

# Setting whitegrid figure style
sns.set_style('whitegrid')

# Plotting
sns.barplot(x='x', y='y', data=df)

# Labeling
plt.title('Whitegrid Figure Style', weight='bold', fontsize=18)
plt.xlabel('x', fontsize=14)

# Displaying the plot
plt.show()
python

Whitegrid

2. Dark and White

Let us consider a function, f(x), and its given value, x. We need to plot f(x) against x and emphasize the function lines rather than the background.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Setting figure size
plt.figure(figsize=(8, 5))

# Initializing the data
x = np.arange(100)
df = pd.DataFrame({'x': x,
                  'Fx': np.sin(2*np.pi*x)})

# Setting dark figure style
sns.set_style('dark')

# Plotting
sns.lineplot(x='x', y='Fx', data=df, color='g')

# Labeling
plt.title('Dark Figure Style', weight='bold', fontsize=18)
plt.xlabel('x', fontsize=14)
plt.ylabel('Fx', fontsize=14)

# Displaying the plot
plt.show()
python

Dark

As we can observe, the function curve lines can be easily separated out from the background. In a similar way, we can built a white figure style plot. In the above code, instead of sns.set_style('dark'), write sns.set_style('white'). The output is shown below:

White

3. Ticks

Ticks provide an additional structure to a plot. Therefore, it depends on the user where one needs to deploy them. Here's a small example with the implementation of ticks figure style.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Initializing the data
x = np.array([9, 50, 2])
y = np.array([85, 44, 25])
z = np.array([32, 65, 12])
df = pd.DataFrame({'x': x, 'y': y, 'z': z})

# Setting ticks figure style
sns.set_style('ticks')

# Plotting
sns.pairplot(df)

# Displaying the plot
plt.show()
python

Ticks

Taking Control of Figure Style Temporarily

Many times, it is required that you don't interfere with the original settings of the program and, therefore, in such a scenario the keyword with helps to bring changes temporarily.

Using the with keyword, you can change the figure style only for one plot at a time without hindering the settings of the overall program. Let us explore this using an example where we initially set darkgrid, but try to create a plot with whitegrid using the with keyword, followed by another plot (which will have no effect from the whitegrid).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Setting the first figure size
plt.figure(0, figsize=(8, 5))

# Initializing the data
x = np.array([9, 50, 2])
y = np.array([85, 44, 25])
z = np.array([32, 65, 12])
df = pd.DataFrame({'x': x, 'y': y, 'z': z})

# Setting darkgrid figure style for complete program
sns.set_style('darkgrid')

# Plotting with whitegrid figure style
with sns.axes_style('whitegrid'):
    sns.barplot(x='x', y='y', data=df)

# Setting the second figure size
plt.figure(1, figsize=(8, 5))

# Plotting with base figure style (darkgrid) 
sns.lineplot(x='x', y='y', data=df)

# Displaying the plot
plt.show()
python

First

Second

As you can observe, the first figure style has not been affected by the global figure style. Notice, we have to use axes_style along with the with keyword, the set_style keyword will result in an AttributeError.

Removing Axes Splines

In many publications, you may have come across to figures with partial axes i.e., one or two axes removed out of all four axes. Such a task can be achieved in Seaborn using a method, despline. By default, it removes the top and right axes, however, it also provides flexibility to remove or retain all four axes as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Setting the first figure size
plt.figure(0, figsize=(8, 5))

# Initializing the data
x = np.arange(200)
y = np.sin(2 * np.pi * x)
df = pd.DataFrame({'x': x, 'y': y})

# Setting ticks figure style
sns.set_style('ticks')

# Plotting
sns.lineplot(x='x', y='y', data=df)

# Removing right and top axes
sns.despine()

# Labelling
plt.title('Figure without top and right axes', weight='bold', fontsize=18)

# Displaying the plot
plt.show()
python

despine

If you want to remove the left and bottom axes too, then pass sns.despine(left=True, bottom=True).

Overriding Elements of the Seaborn Styles

You can also override the elements of a figure by passing a new value to the available parameters in sns.axes_style() method. If you simply execute this method then it will return all the default values for its elements.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# Fetching all the default values of elements
sns.axes_style()

# OUTPUT
# {'axes.axisbelow': True,
#  'axes.edgecolor': '.15',
#  'axes.facecolor': 'white',
#  'axes.grid': False,
#  'axes.labelcolor': '.15',
#  'axes.spines.bottom': True,
#  'axes.spines.left': True,
#  'axes.spines.right': True,
# ...
# ...
# ...
#  'xtick.color': '.15',
#  'xtick.direction': 'out',
#  'xtick.top': False,
#  'ytick.color': '.15',
#  'ytick.direction': 'out',
#  'ytick.left': True,
#  'ytick.right': False}
python

Here's an illustration which will allow you to modify any of these elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# Setting the first figure size
plt.figure(0, figsize=(8, 5))

# Initializing the data
x = np.arange(200)
y = np.sin(2 * np.pi * x)
df = pd.DataFrame({'x': x, 'y': y})

# Overriding elements value
sns.set_style('white', 
              {'axes.grid': True,
               'grid.color': '.5',
               'grid.linestyle': '--',
               'axes.spines.left': False,
               'axes.spines.right': False,
               'axes.spines.top': False,
              })

# Plotting
sns.lineplot(x='x', y='y', data=df)

# Labelling
plt.title('Overriding Default Elements Value', weight='bold', fontsize=18)

# Displaying the plot
plt.show()
python

Overriding

Conclusion

In this guide, you have learned about setting various built-in figure styles, handling axes, and overriding built-in elements value of a Seaborn figure.

To learn more about Seaborn, you can refer the following guides:

0