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

如何在Filament环形图组件中移除坐标轴刻度并始终显示标签值

解决Filament环形图(Doughnut ChartWidget)的两个自定义需求

针对你使用Filament 3.x自定义环形图的两个需求,以下是具体实现方案:

a) 移除x、y坐标轴刻度

环形图无需坐标轴,只需在ChartWidget类中通过getOptions()方法关闭坐标轴显示即可:

use Filament\Widgets\ChartWidget;

class CustomDoughnutChart extends ChartWidget
{
    protected static ?string $heading = '自定义环形图';

    // 数据获取逻辑
    protected function getData(): array
    {
        return [
            'datasets' => [
                [
                    'label' => '数据统计',
                    'data' => [30, 50, 20],
                    'backgroundColor' => ['#FF6384', '#36A2EB', '#FFCE56'],
                ],
            ],
            'labels' => ['分类A', '分类B', '分类C'],
        ];
    }

    // 指定图表类型为环形图
    protected function getType(): string
    {
        return 'doughnut';
    }

    // 配置图表选项,关闭坐标轴显示
    protected function getOptions(): array
    {
        return [
            'scales' => [
                'x' => ['display' => false],
                'y' => ['display' => false],
            ],
        ];
    }
}

通过scales配置将x、y轴的display设为false,即可完全隐藏坐标轴及刻度。

b) 始终显示标签和值

要让环形图每个扇区始终显示标签和数值,可使用Filament已集成的Chart.js datalabels插件,在getOptions()中配置插件参数:

protected function getOptions(): array
{
    return [
        'scales' => [
            'x' => ['display' => false],
            'y' => ['display' => false],
        ],
        'plugins' => [
            // 关闭默认悬停提示(可选,若需保留可注释此行)
            'tooltip' => ['enabled' => false],
            'datalabels' => [
                'display' => true,
                // 自定义显示格式:标签 + 值
                'formatter' => function($value, $context) {
                    return $context->chart->data->labels[$context->dataIndex] . ': ' . $value;
                },
                'color' => '#ffffff', // 文字颜色
                'font' => [
                    'weight' => 'bold',
                    'size' => 12,
                ],
            ],
        ],
    ];
}

配置后,每个环形扇区会直接显示对应的标签和数值,无需鼠标悬停触发。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 12:55:55