Controlling text/label placement with check_overlap

The check_overlap parameter in geom_text() and geom_label() is used to prevent overlapping text labels in the same layer.

In [1]:
import pandas as pd
from lets_plot import *
In [2]:
LetsPlot.setup_html()
In [3]:
mpg = pd.read_csv ("https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg.csv")
mpg.head(3)
Out[3]:
Unnamed: 0 manufacturer model displ year cyl trans drv cty hwy fl class
0 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compact
1 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compact
2 3 audi a4 2.0 2008 4 manual(m6) f 20 31 p compact
In [4]:
p = ggplot(mpg, aes('displ', 'hwy')) + \
    theme(legend_position = "none", panel_background=element_rect(fill="#CCCCCC")) + \
    ggsize(600, 400)

Without check_overlap: The default behavior plots all labels, which can result in an overcrowded plot.

In [5]:
p + geom_text(aes(label='class', color='class'))
Out[5]:

With check_overlap=True: Text labels that overlap existing labels are not rendered. The labels are processed in the order they appear in the data frame, and if a subsequent label would overlap with a previous one, it is omitted.

In [6]:
p + geom_text(aes(label='class', color='class'), check_overlap=True)
Out[6]:

check_overlap is also applicable for geom_label.

In [7]:
p + geom_label(aes(label='class'), check_overlap=True)
Out[7]: