In this post, you'll learn the absolute quickest path to create beautiful data visualizations in Python. Specifically, we will be issuing a command from Seaborn, a popular library for creating static two-dimensional plots. We begin by reading in some data from Airbnb listings in Washington D.C.
import pandas as pd
df = pd.read_csv('../../data/airbnb.csv',
usecols=['neighborhood', 'accommodates', 'price'])
df.head()
Here, we will use Seaborn to create a box plot of prices by neighborhood splitting by the number of persons the space accommodates.
import seaborn as sns
sns.boxplot(x='neighborhood', y='price', hue='accommodates', data=df);
set_theme
function¶While the default plot settings are not bad, they can be improved upon using a single command and that is with the set_theme
function in Seaborn. By default, it will use the darkgrid style along with the deep color palette.
sns.set_theme()
After running this command, the same plot will appear substantially different.
sns.boxplot(x='neighborhood', y='price', hue='accommodates', data=df);
You may call the set_theme
function without arguments, but I suggest increasing the DPI (dots per square inch) and reducing the font scale. The default DPI is 100 for matplotlib (the library Seaborn uses for all of its plotting), which is a lower resolution than most modern monitors and is the reason why the default image size (6.4 inches by 4.8 inches) does not match the actual screen inches on your monitor.
Any plot settings (formally, the matplotlib run configuration parameters) are able to changed with the rc
parameter. Here, the DPI is increased to 150 and the default figure size decreased.
sns.set_theme(rc={'figure.dpi': 150, 'figure.figsize': (5, 3.75)})
sns.boxplot(x='neighborhood', y='price', hue='accommodates', data=df);
While the image is sharper and larger, the text is clearly too big. The set_theme
function provides a font_scale
parameter to decrease the relative size of the text in the image. Here we set it to 0.65.
sns.set_theme(rc={'figure.dpi': 150, 'figure.figsize': (5, 3.75)}, font_scale=0.65)
sns.boxplot(x='neighborhood', y='price', hue='accommodates', data=df);
There are several built-in styles (white, dark, whitegrid, darkgrid, ticks) as well as color palettes (deep, muted, bright, pastel, dark, colorblind) available as well. Here, we choose the whitegrid style paired with the pastel color palette.
sns.set_theme(style='whitegrid',
palette='pastel',
rc={'figure.dpi': 150, 'figure.figsize': (5, 3.75)},
font_scale=0.65)
sns.boxplot(x='neighborhood', y='price', hue='accommodates', data=df);
In summary, use the set_theme
function in Seaborn to easily choose a style, color palette, customize the matplotlib run configuration settings and to scale the font.
Upon registration, you'll get access to the following free courses: