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

在ASP.NET中通过Google Charts API调整堆叠条形图负向标签位置

解决方案

要实现负值条形的注释显示在下方(并展示实际正值)、正值条形注释保留在上方的效果,需要从注释内容格式化和注释位置配置两个核心点修改代码:


1. 自定义注释计算逻辑(修正显示数值)

原代码中直接使用"stringify"会显示原始负值(比如-676),我们需要自定义calc函数,对2022年的负值数据取绝对值后展示实际业务数值:

var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
    {
        calc: function (dt, row) {
            // 2023年正值数据直接返回原数值
            return dt.getValue(row, 1).toString();
        },
        sourceColumn: 1,
        type: "string",
        role: "annotation"
    },
    2,
    {
        calc: function (dt, row) {
            // 2022年负值数据取绝对值,显示实际业务数值
            return Math.abs(dt.getValue(row, 2)).toString();
        },
        sourceColumn: 2,
        type: "string",
        role: "annotation"
    },
    3,
    {
        calc: "stringify",
        sourceColumn: 3,
        type: "string",
        role: "annotation"
    }
]);

2. 为不同系列配置注释位置

在options的series配置中,分别给两个条形系列指定注释位置:

series: {
    0: { 
        targetAxisIndex: 0, 
        color: 'blue',
        annotations: {
            position: 'above' // 正值条形注释固定在上方
        }
    },
    1: { 
        targetAxisIndex: 0, 
        color: 'gray',
        annotations: {
            position: 'below' // 负值条形注释固定在下方
        }
    },
    2: { 
        targetAxisIndex: 1, 
        color: 'red', 
        type: 'line', 
        lineWidth: 1, 
        lineDashStyle: [4, 4], 
        pointSize: 5 
    },
},

3. 可选:优化注释视觉效果

如果注释和条形出现重叠,可添加注释茎部长度调整间距:

annotations: {
    highContrast: false,
    textStyle: {
        color: 'red',
        fontSize: 12,
        bold: true
    },
    alwaysOutside: true,
    stem: {
        length: 5 // 增加注释与条形的间距
    }
},

修改后的完整代码

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
    google.charts.load('current', { packages: ['corechart'] });
    google.charts.setOnLoadCallback(drawChart);

    function drawChart() {
        var data = new google.visualization.DataTable();

        var jsonList = @(Json.Serialize(Model.listAllAircraftChartQuarterly))

        var title = 'Quarterly Aircraft Transaction Trend';

        data.addColumn('string', 'Quarter');
        data.addColumn('number', '2023');
        data.addColumn('number', '2022');
        data.addColumn('number', '% Change');
        data.addRows(jsonList.map((p) => {
            return [p.yearQuarter, p.year2top, p.year3bottom, p.year2percent];
        }));

        var formatPercent = new google.visualization.NumberFormat({ pattern: '#.#%' });
        formatPercent.format(data, 3);

        var view = new google.visualization.DataView(data);
        view.setColumns([0, 1,
            {
                calc: function (dt, row) {
                    return dt.getValue(row, 1).toString();
                },
                sourceColumn: 1,
                type: "string",
                role: "annotation"
            },
            2,
            {
                calc: function (dt, row) {
                    return Math.abs(dt.getValue(row, 2)).toString();
                },
                sourceColumn: 2,
                type: "string",
                role: "annotation"
            },
            3,
            {
                calc: "stringify",
                sourceColumn: 3,
                type: "string",
                role: "annotation"
            }
        ]);
        var options = {
            title: title,
            titlePosition: 'out',
            isStacked: true,

            seriesType: "bars",
            vAxes: {
                0: {
                    textPosition: 'out',
                    viewWindowMode: 'pretty',
                    title: "",
                    viewWindow: { min: -1100, max: 1100 },
                    gridlines: { color: 'lightgray' },
                },
                1: {
                    textPosition: 'out',
                    viewWindow: { min: -1, max: 1 },
                    format: 'percent',
                    gridlines: { color: 'transparent' }
                },
            },
            series: {
                0: { 
                    targetAxisIndex: 0, 
                    color: 'blue',
                    annotations: {
                        position: 'above'
                    }
                },
                1: { 
                    targetAxisIndex: 0, 
                    color: 'gray',
                    annotations: {
                        position: 'below'
                    }
                },
                2: { 
                    targetAxisIndex: 1, 
                    color: 'red', 
                    type: 'line', 
                    lineWidth: 1, 
                    lineDashStyle: [4, 4], 
                    pointSize: 5 
                },
            },
            width: '100%',
            height: '300',

            legend: { position: 'top' },
            chartArea: {
                height: '100%',
                width: '100%',
                top: 48,
                left: 60,
                right: 60,
                bottom: 75
            },
            annotations: {
                highContrast: false,
                textStyle: {
                    color: 'red',
                    fontSize: 12,
                    bold: true
                },
                alwaysOutside: true,
                stem: {
                    length: 5
                }
            },
        }

        var chart = new google.visualization.ComboChart(document.getElementById('primaryYear2and3'));
        chart.draw(view, options);

        document.getElementById('downloadimg2and3').innerHTML = '<a download="google-chart-image" href="' + chart.getImageURI() +
            '"><button type="button" class="btn btn-outline-dark btn-sm opacity-25 ms-4 mb-3">Download Chart Image</button></a>';

        window.addEventListener('resize', drawChart, false);
    }
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 16:35:09