PlotlyJS中椭圆旋转实现咨询:支持旋转角度或自定义端点吗?
Plotly 椭圆绘制:旋转角度与自定义顶点实现
一、支持围绕中心定义椭圆旋转角度
Plotly原生的ellipse形状(通过fig.add_shape(type='ellipse')添加)默认与x/y轴对齐,没有直接的rotation参数,但可以通过自定义SVG路径实现旋转椭圆。
比如要绘制中心在(x0, y0),长半轴a,短半轴b,旋转角度θ(弧度)的椭圆,可直接用SVG路径的椭圆指令定义:
import plotly.graph_objects as go import math fig = go.Figure() x0, y0 = 2, 3 a, b = 4, 2 theta = math.pi/4 # 45度旋转 # 用SVG路径定义旋转椭圆 fig.add_shape( type="path", path=f"M {x0 + a*math.cos(theta)} {y0 + a*math.sin(theta)} " f"a {a} {b} {theta*180/math.pi} 1 1 {-2*a*math.cos(theta)} {-2*a*math.sin(theta)} " f"a {a} {b} {theta*180/math.pi} 1 1 {2*a*math.cos(theta)} {2*a*math.sin(theta)}", line_color="blue", fillcolor="rgba(0,0,255,0.1)" ) fig.show()
也可以生成旋转后椭圆上的一系列点,用scatter trace绘制闭合曲线,这种方法更直观,适合需要精确控制的场景。
二、通过四个最外层点绘制椭圆
如果你已知椭圆的四个最外层顶点(长轴两端点、短轴两端点),可以先推导椭圆的核心参数,再生成图形:
- 中心坐标:长轴两点的中点
- 长半轴长度:长轴两点距离的一半
- 短半轴长度:短轴两点距离的一半
- 旋转角度:长轴与x轴的夹角
得到参数后,即可用自定义路径或点集绘制椭圆。如果不想手动推导参数,也可以直接用四个顶点拟合椭圆方程,生成足够多的点后用scatter绘制闭合曲线。
举个示例,假设四个顶点为(4,5)、(0,1)、(2,6)、(2,0):
import plotly.graph_objects as go import math import numpy as np # 四个顶点 p1, p2, p3, p4 = (4,5), (0,1), (2,6), (2,0) # 计算中心、半轴和旋转角度 x0 = (p1[0] + p2[0])/2 y0 = (p1[1] + p2[1])/2 a = math.sqrt((p1[0]-p2[0])**2 + (p1[1]-p2[1])**2)/2 b = math.sqrt((p3[0]-p4[0])**2 + (p3[1]-p4[1])**2)/2 theta = math.atan2(p2[1]-p1[1], p2[0]-p1[0]) # 生成椭圆上的点 t = np.linspace(0, 2*math.pi, 100) x = x0 + a*np.cos(t)*math.cos(theta) - b*np.sin(t)*math.sin(theta) y = y0 + a*np.cos(t)*math.sin(theta) + b*np.sin(t)*math.cos(theta) fig = go.Figure() fig.add_scatter(x=x, y=y, mode='lines', name='椭圆') # 标记四个顶点 fig.add_scatter(x=[p1[0],p2[0],p3[0],p4[0]], y=[p1[1],p2[1],p3[1],p4[1]], mode='markers', name='顶点') fig.show()
内容的提问来源于stack exchange,提问作者Mohamed Yehia
相关产品推荐
相关产品推荐

