1

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
ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
Brad
  • 580
  • 4
  • 19
  • Unfortunately, this seemed like the best example I could find: https://stackoverflow.com/questions/41980772/equivalent-of-abline-in-plotly Perhaps it's a bit easier using ggplotly, but I cannot vouch for that. – joncgoodwin Oct 26 '21 at 00:00
  • If you're looking for a trend line in plotly (which is the role abline fills, this [Q & A](https://stackoverflow.com/questions/38593153/plotly-regression-line-r) might help. – Kat Oct 26 '21 at 00:20
  • Possibly cheating, but : `library(plotly); library(ggplot); fig <- ggplot(iris, aes(x = Sepal.Length, y = Petal.Length)) + geom_point() + geom_abline(); ggplotly(fig)` – Jon Spring Oct 26 '21 at 00:20
  • 1
    You may try `add_segments`. Try `p <- plot_ly(data = iris, x = ~Sepal.Length, y = ~Petal.Length, type = "scatter") %>% add_segments(x=4, y=4, xend = 8, yend = 8) p ` – Park Oct 26 '21 at 00:27
  • @Brad old question - nevertheless, I left an approach below. – ismirsehregal Apr 08 '22 at 10:57

2 Answers2

3

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.

ismirsehregal
  • 30,045
  • 5
  • 31
  • 78
0

Kindly let me know if this is what you were anticipating.

fit <- lm(Petal.Length ~ Sepal.Length, data = iris)

iris %>% 
  plot_ly(x = ~Sepal.Length) %>% 
  add_markers(y = ~Petal.Length) %>% 
  add_lines(x = ~Sepal.Length, y = fitted(fit))
  • This is a linear model. I want a line x = y which is uninfluenced by any data points. – Brad Jan 17 '22 at 22:39