gpt4 book ai didi

r - 相当于 abline 在 plotly

转载 作者:行者123 更新时间:2023-12-04 12:25:12 24 4
gpt4 key购买 nike

我想向 plotly 添加一条线(不仅仅是垂直或水平)图表

library(plotly)
d = data.frame(x=1:10, y=1:10)
plot_ly(d, x = ~x, y = ~y, type='scatter')

说我想要 (D) y = 2x作为一条线,我可以在不自己生成数据的情况下在 d 的另一列中进行绘图

最佳答案

至少有两种模拟方式 abline .

  • 添加另一条轨迹,起点和终点
  • 添加 line形状到layout带有起点和终点

  • 缺点是 minmax需要计算每个跟踪( Plotly 无论如何都需要这样做,但它会使代码膨胀)。

    另一种方法是绘制从一个极端到另一个极端的线,然后设置 xaxisyaxis range手动。

    在下面的示例中,红线是添加的轨迹,而黑线是通过 shape 添加的。 line .

    enter image description here
    library('plotly')

    #a function to calculate your abline
    p_abline <- function(x, a=2, b=-5){
    y <- a * x + b
    return(y)
    }

    #create an empty plot
    p <- plot_ly()

    #list with all your x and y values
    x <- list(c(1,2,3), c(2,3,6), (1:5))
    y <- list(c(1,2,3), c(0,5,10), sample(-10:10, 5))

    #loop through the x/y values and determine min/max
    for (i in 1:length(x)) {
    p<-add_trace(p, y=y[[i]], x=x[[i]] , type="scatter", mode="markers+lines")
    if (i == 1 || max(x[[i]]) > max_x) {
    max_x = max(x[[i]])
    }
    if (i == 1 || max(y[[i]]) > max_y) {
    max_y = max(y[[i]])
    }
    if (i == 1 || min(x[[i]]) < min_x) {
    min_x = min(x[[i]])
    }
    if (i == 1 || min(y[[i]]) < min_y) {
    min_y = min(y[[i]])
    }

    }

    #add a trace to simulate abline
    p<-add_trace(p, x=c(min_x, max_x), y=c(p_abline(min_x), p_abline(max_x)) , type="scatter", mode="lines", name='abline')

    #add a shape (line) to simulate abline
    p <- p %>% layout(
    shapes=list(type='line', x0=min_x, x1=max_x, y0=p_abline(min_x, -1, 3), y1=p_abline(max_x, -1, 3))
    )

    p

    关于r - 相当于 abline 在 plotly,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980772/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com