繁体   English   中英

如何在折线图C#中为负数据点绘制不同的颜色

[英]How to plot different colour for negative datapoint in line chart c#

我想通过datagridview创建折线图,我需要红色绘图线表示负值,绿色需要画线。 我编写了代码,但是所有数据点都只有绿色。

foreach (DataGridViewRow row in dgvReport.Rows)
{ 
    decimal val = 0;
    val = Convert.ToDecimal(row.Cells[8].Value.ToString());

    if (val < 0)
    {
        Dchart.Series[0].Color = System.Drawing.Color.Red;
    }

    if (val > 0)
    {
        Dchart.Series[0].Color = System.Drawing.Color.Green;
    }

    Dchart.Series[0].Points.AddXY(row.Cells[0].Value.ToString(), row.Cells[8].Value.ToString());
    Dchart.ChartAreas[0].AxisX.Interval = 3;
}

您需要分别为每个DataPoint着色:

int index = Dchart.Series[0].Points.AddXY(row.Cells[0].Value,
                                          row.Cells[8].Value);
DataPoint newPoint = Dchart.Series[0].Points[index];
newPoint.Color = newPoint.YValues[0] < 0 ? Color.Red : Color.Green;

请注意,颜色仅进入一行!

另请注意,您的转换狂欢并不是真正需要的。

最后说明:您将所有值添加为strings 这是一个严重的错误! 这样做将丢失所有x值,并导致y值的默认转换不受控制。

始终所有值添加为数字或DateTimes

如果发现需要将单元格值objects转换为数字,请这样做,并整体创建DataPoint ,最好在添加有series.Add()之前将其包括Color!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM