Search code examples
rplotplotlyr-plotlyabline

Plotly in R - Diagonal AB line


I require a diagonal line through the origin of this plot

Something similar to ggplot2's geom_abline(intercept = 0 , slope = 1) But for plotly in R

library(plotly)

fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
fig

Solution

  • A line shape could be used to achive this:

    library(plotly)
    
    fig <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length)
    fig %>%
      layout(shapes = list(list(
        type = "line", 
        x0 = 0, 
        x1 = ~max(Sepal.Length, Petal.Length), 
        xref = "x",
        y0 = 0, 
        y1 = ~max(Sepal.Length, Petal.Length),
        yref = "y",
        line = list(color = "black")
      )))
    

    result

    Also see this related answer.

    Btw. via xref = "paper" we don't need to specify start and end points for the line, however the line is no longer aligned with the axes.