Expanding Plot Limits with expand_limits()

When creating visualizations, you might occasionally need to adjust your plot boundaries to encompass specific data points or values. This is where the expand_limits() function comes in handy. It allows you to extend the plot's scales to include particular values, ensuring they're visible in your visualization.

In [1]:
from lets_plot import *
import pandas as pd
In [2]:
LetsPlot.setup_html()
In [3]:
mpg = pd.read_csv('https://raw.githubusercontent.com/JetBrains/lets-plot-docs/master/data/mpg2.csv')
mpg.head(3)
Out[3]:
miles per gallon number of cylinders engine displacement (cu. inches) engine horsepower vehicle weight (lbs.) time to accelerate (sec.) model year origin of car vehicle name
0 18.0 8 307.0 130 3504 12.0 70 US chevrolet chevelle malibu
1 15.0 8 350.0 165 3693 11.5 70 US buick skylark 320
2 18.0 8 318.0 150 3436 11.0 70 US plymouth satellite
In [4]:
p = ggplot(mpg, aes("miles per gallon", "vehicle weight (lbs.)")) + geom_point()   
p
Out[4]:

Expand Lower Limit Along the x-axis

In [5]:
p + expand_limits(x=0)
Out[5]:

Expand Limits Along the y-axis

In [6]:
p + expand_limits(y=[1000, 9000])
Out[6]:

Expand Lower Limits Along Both Axes

In [7]:
p + expand_limits(x = 0, y = 0)
Out[7]:

Expanding Color-scale Limits

In [8]:
# Add color mapping
p1 = p + aes(color="number of cylinders")

gggrid([
    p1, 
    # Expand the color-scale limits.
    p1 + expand_limits(color=range(2, 11, 2))
])    
Out[8]: