from plotnine import aes, annotate, facet_wrap, ggplot, geom_point
from plotnine.data import mtcars
from plotnine.helpers import get_aesthetic_limits
In [1]:
Here we create a plot, get the current limits and add annotations using the values of the limits.
In [2]:
= (
p "wt", "mpg"))
ggplot(mtcars, aes(+ geom_point()
)
= get_aesthetic_limits(p, "x")
x_limits = get_aesthetic_limits(p, "y")
y_limits
(
p+ annotate("vline", xintercept=x_limits, color="green")
+ annotate("text", x=x_limits, y=y_limits, label=["low", "high"], ha=["left", "right"], color="purple")
)
We got the limits before facetting
In [3]:
(
p+ annotate("vline", xintercept=x_limits, color="green")
+ annotate("text", x=x_limits, y=y_limits, label=["low", "high"], ha=["left", "right"], color="purple")
+ facet_wrap("cyl")
)
When we call the function facetting, we get list of limits with each panel.
In [4]:
= (
p "wt", "mpg"))
ggplot(mtcars, aes(+ geom_point()
+ facet_wrap("cyl", scales="free_x")
)
= get_aesthetic_limits(p, "x") # limits for 1st, 2nd & 3rd panel
x_limits_lst = x_limits_lst[1] # limits of the 2nd panel
x_limits
(
p+ annotate(
"rect",
=x_limits[0],
xmin=x_limits[1],
xmax=-float("inf"),
ymin=float("inf"),
ymax="green",
fill=.25
alpha
)+ annotate("text", x=x_limits, y=y_limits, label=["low", "high"], ha=["left", "right"], color="purple")
)