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

Windows Form中Chart单系列数据按正负值设置柱状条颜色

Windows窗体Chart控件单Series柱状条按正负值设不同颜色

你的需求是给单个Series里数值大于0的柱状条设绿色,小于0的设深红色,但原代码存在几个问题:

  • 错误地把Series.Points(数据点集合)赋值给int变量,类型不匹配
  • 直接给整个Series设置颜色,所有柱状条会变成同一种颜色,无法实现单个点区分

正确的做法是遍历Series中的每个数据点,根据每个点的数值单独设置颜色,代码如下:

// 遍历Series[0]中的每个数据点
foreach (DataPoint point in chart1.Series[0].Points)
{
    // 获取当前点的Y值(YValues[0]对应柱状条的高度值)
    double value = point.YValues[0];
    if (value > 0)
    {
        point.Color = Color.Green;
    }
    else if (value < 0)
    {
        point.Color = Color.Crimson;
    }
    // 可选:处理数值为0的情况,比如设为灰色
    // else
    // {
    //     point.Color = Color.Gray;
    // }
}

效果说明:执行这段代码后,Chart中数值大于0的柱状条会显示绿色,小于0的显示深红色,和你需要的参考图效果一致(正值绿、负值深红)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 03:15:00