I want to color code the background of my scatterplot, e.g. to classify the data into bad, medium and good areas. Hence, I want the limits of the squares to extend to the figure margins when zooming out.
As to my knowledge, there is not (yet) a hrect()
function as in Python, I wrote a helper function using xref = "paper"
on the X axis.
library("plotly")
fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
hrect <- function(y0 = 0, y1 = 1, fillcolor = "red", opacity = 0.2) {
list(
type = "rect",
x0 = 0,
x1 = 1,
xref = "paper",
y0 = y0,
y1 = y1,
line_width = 0,
fillcolor = fillcolor,
opacity = opacity,
layer = "below"
)
}
fig <- fig |> plotly::layout(shapes = list(
hrect(y0 = 0, y1 = 3, fillcolor = "red"),
hrect(y0 = 3, y1 = 6, fillcolor = "blue"),
hrect(y0 = 6, y1 = 8, fillcolor = "green")
))
fig
This extends the zooming to +/- infinity on the X axis, but I would like to have the same behavior for the upper (green) and lower (red) rectangles on the Y axis. Is it maybe possible to use different yref
s for y0
and y1
?
UPDATE:
Thanks to the comprehensive answer by @SamR, there's an easy work-around for my problem. But to clarify, my question was more if there is a "proper" way to do with plotly
in R.
For illustration, you could achieve this behavior for the red rectangle in ggplot2
by setting xmin
, xmax
and (!) ymin
to +/-Inf
:
library("ggplot2")
gg <- ggplot()
gg <- gg + geom_rect(
aes(
xmin = -Inf,
xmax = Inf,
ymin = -Inf,
ymax = 3),
fill = 2,
alpha = 0.2
)
gg <- gg + geom_point(
data = iris,
aes(
x = Sepal.Length,
y = Petal.Length)
)
gg <- gg + coord_cartesian(
xlim = c(-10, 10),
ylim = c(-10, 10)
)
gg