You need to enable JavaScript to run this app. 如何在C# WPF中使用OxyPlot绘制指定旋转角度的椭圆
优惠活动
大模型
产品
解决方案
定价
更多

如何在C# WPF中使用OxyPlot绘制指定旋转角度的椭圆

OxyPlot 带旋转属性的95%置信椭圆实现方案

OxyPlot是面向.NET的跨平台绘图库,使用便捷,适合各类图表绘制场景。
在XY散点图上叠加95%置信椭圆是数据分析类需求中的常见展示逻辑,但原生OxyPlot组件存在以下限制,无法直接实现:

  • OxyPlot.Annotations命名空间下提供的EllipseAnnotation注解仅支持基础椭圆属性配置,未开放旋转相关的属性或方法
  • IRender提供的可重写绘制方法没有double类型的旋转角度入参,官方文档也未给出直接的实现方案

我此前在相关开发实践中验证了可行的实现方案,核心逻辑是自定义注解类重写渲染逻辑,参考代码如下:

using OxyPlot;
using OxyPlot.Annotations;
using OxyPlot.Axes;

public class RotatableEllipseAnnotation : Annotation
{
    /// <summary>
    /// 椭圆中心点X坐标(数据坐标)
    /// </summary>
    public double CenterX { get; set; }
    /// <summary>
    /// 椭圆中心点Y坐标(数据坐标)
    /// </summary>
    public double CenterY { get; set; }
    /// <summary>
    /// 椭圆长半轴长度
    /// </summary>
    public double SemiMajorAxis { get; set; }
    /// <summary>
    /// 椭圆短半轴长度
    /// </summary>
    public double SemiMinorAxis { get; set; }
    /// <summary>
    /// 椭圆旋转角度(单位:弧度)
    /// </summary>
    public double RotationAngle { get; set; }
    /// <summary>
    /// 椭圆边框颜色
    /// </summary>
    public OxyColor StrokeColor { get; set; } = OxyColors.Black;
    /// <summary>
    /// 椭圆边框粗细
    /// </summary>
    public double StrokeThickness { get; set; } = 1;
    /// <summary>
    /// 椭圆填充颜色
    /// </summary>
    public OxyColor FillColor { get; set; } = OxyColors.Transparent;

    public override void Render(IRenderContext rc)
    {
        // 采样生成椭圆顶点,采样点数可根据精度需求调整
        const int sampleCount = 100;
        var ellipsePoints = new List<ScreenPoint>(sampleCount);

        for (int i = 0; i < sampleCount; i++)
        {
            double radian = 2 * Math.PI * i / sampleCount;
            // 计算未旋转状态下的椭圆相对坐标
            double relativeX = SemiMajorAxis * Math.Cos(radian);
            double relativeY = SemiMinorAxis * Math.Sin(radian);
            // 应用旋转矩阵变换
            double rotatedX = relativeX * Math.Cos(RotationAngle) - relativeY * Math.Sin(RotationAngle);
            double rotatedY = relativeX * Math.Sin(RotationAngle) + relativeY * Math.Cos(RotationAngle);
            // 转换为数据坐标后映射到屏幕坐标
            var dataPoint = new DataPoint(CenterX + rotatedX, CenterY + rotatedY);
            ellipsePoints.Add(Transform(dataPoint));
        }

        // 绘制椭圆
        rc.DrawPolygon(ellipsePoints, FillColor, StrokeColor, StrokeThickness);
    }
}

使用时只需要先根据散点样本计算出95%置信椭圆的中心、长短半轴、旋转角度,再实例化该自定义注解添加到PlotModel的Annotations集合即可。欢迎大家补充更多可行解法。


内容的提问来源于stack exchange,提问作者Nitish Kumar Pal

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.16 11:06:04