You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MudBlazor的MudChart中添加垂直线?

在MudBlazor的MudChart中添加垂直线(通过CustomGraphics实现)

你推测的没错,<CustomGraphics>确实是实现这个需求的正确方式——它允许直接嵌入SVG元素,而垂直线本质就是SVG的<line>标签。下面是具体的实现步骤和代码示例:

1. 基础静态垂直线实现

如果只需要固定位置的垂直线,直接在<CustomGraphics>中添加SVG的<line>元素即可:

<MudChart ChartOptions="@(new() { ChartPalette = new[] { "#9E9E9E" } })"
          ChartType="ChartType.Bar"
          ChartSeries="@Series"
          @bind-SelectedIndex="Index"
          XAxisLabels="@XAxisLabels"
          Width="100%"
          Height="300px">
    <CustomGraphics>
        <!-- 红色虚线垂直线,x坐标固定为150px,贯穿整个图表高度 -->
        <line x1="150" x2="150" y1="0" y2="300" 
              stroke="#ff0000" stroke-width="2" stroke-dasharray="5,3" />
    </CustomGraphics>
</MudChart>

2. 动态匹配X轴标签的垂直线

如果需要让垂直线精准对应某个X轴标签的位置,需要通过MudChart的引用获取图表的刻度信息,动态计算x坐标:

第一步:定义图表引用和变量

@code {
    private MudChart _chartRef;
    private double _targetLineX;
    // 你的Series、Index、XAxisLabels定义...
}

第二步:绑定引用并添加动态垂直线

<MudChart @ref="_chartRef"
          ChartOptions="@(new() { ChartPalette = new[] { "#9E9E9E" } })"
          ChartType="ChartType.Bar"
          ChartSeries="@Series"
          @bind-SelectedIndex="Index"
          XAxisLabels="@XAxisLabels"
          Width="100%"
          Height="300px">
    <CustomGraphics>
        <!-- 动态计算位置的垂直线 -->
        <line x1="@_targetLineX" x2="@_targetLineX" 
              y1="@_chartRef?.ChartJs.ChartInstance?.Chart.Scales.Y.GetPixelForValue(_chartRef.ChartJs.ChartInstance.Chart.Scales.Y.Min)"
              y2="@_chartRef?.ChartJs.ChartInstance?.Chart.Scales.Y.GetPixelForValue(_chartRef.ChartJs.ChartInstance.Chart.Scales.Y.Max)"
              stroke="#2196F3" stroke-width="2" />
    </CustomGraphics>
</MudChart>

第三步:在渲染后计算目标位置

protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender && _chartRef != null)
    {
        var chartInstance = _chartRef.ChartJs.ChartInstance?.Chart;
        if (chartInstance != null)
        {
            // 示例:让垂直线对应第2个X轴标签(索引从0开始)
            int targetLabelIndex = 1;
            var xScale = chartInstance.Scales.X;
            // 获取该标签对应的像素x坐标
            _targetLineX = xScale.GetPixelForValue(targetLabelIndex);
            StateHasChanged();
        }
    }
    await base.OnAfterRenderAsync(firstRender);
}

关键参数说明

  • x1/x2:设置为相同值即可生成垂直线,静态值直接写像素,动态值通过图表刻度计算
  • y1/y2:控制垂直线的上下范围,用图表Y轴的最小/最大值对应的像素可以让线条精准覆盖绘图区域
  • stroke:设置线条颜色,stroke-width设置线条粗细,stroke-dasharray可以实现虚线效果(如"5,3"表示5px实线+3px空白)

内容的提问来源于stack exchange,提问作者blaert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 01:45:00