首页 > 解决方案 > 用 plotly 绘制圆线段

问题描述

我想用plotly给定的中心点和半径绘制一个圆弧段。

我在 plotly 文档中找不到任何方法,并尝试了以下代码,该代码有效,但我不想看到中间点。

我目前的尝试:

library(plotly)

from <- 0
to <-  180
by <- (to-from)/10

t <- seq(from*pi/180, to*pi/180 , by*pi/180)

x0 <- 1
y0 <- 1
r <- 5
y <- y0 + r*sin(t)
x <- x0 + r*cos(t)

plotly::plot_ly() %>% 
  add_trace(x=~x, y = ~y, line = list(shape = "spline"))

在此处输入图像描述

我想看到的:

在此处输入图像描述

有什么提示吗?之后是否可以删除中间点?或者直接用 plotly 绘制一个“完美”的圆圈?先感谢您!

标签: rplotlydata-visualization

解决方案


您可以使用layoutwithcircle形状:

library(plotly)
plot_ly() %>% layout(shapes = list(
                list(type = 'circle',
                     xref = 'x', x0 = -4, x1 = 6,
                     yref = 'y', y0 =  -4, y1 = 6,
                     line = list(color = 'blue'))),
                     yaxis = list(range=c(1,6.5)))

在此处输入图像描述

仅绘制一个半圆的另一种选择是使用line形状(具有更多段:) by <- (to-from)/100

line <- list(
  type = "line",
  line = list(color = "blue"),
  xref = "x",
  yref = "y"
)

lines <- list()

for (i in 2:length(t)) {
  line[["x0"]] <- x[i-1]
  line[["x1"]] <- x[i]
  line[["y0"]] <- y[i-1]
  line[["y1"]] <- y[i]
  lines <- c(lines, list(line))
}

library(plotly)
plot_ly() %>% layout(shapes = lines,
                     yaxis = list(range=c(0,6.5)))

在此处输入图像描述


推荐阅读