Search code examples
c#chartsdundas

Dundas Charting C# conditional colour rules on column


I am using Dundas Charts in Visual Studio using C#.

I have a chart with one series - the chart is displaying the series on columns. I am currently using the following code to add the series:

    public void AddSeries(string name, SeriesChartType type, IEnumerable xValues, IEnumerable yValues, bool showLabels = true)
    {
        Series s = new Series();
        s.Points.DataBindXY(xValues, yValues);
        s.LegendText = name;
        s.Type = type;
        if (type == SeriesChartType.Line) s.Color = Color.FromArgb(139,0,0);
        else s.Color = _palette[_chart.Series.Count < _palette.Length ? _chart.Series.Count : 0];
        s.ShowLabelAsValue = showLabels;
        s.FontAngle = -90;
        s.LabelFormat = string.IsNullOrWhiteSpace(_chart.ChartAreas["Default"].AxisY.LabelStyle.Format) ? "P0" : _chart.ChartAreas["Default"].AxisY.LabelStyle.Format;
        s.Font = new Font("Arial", 5);

        _chart.Series.Add(s);
    }

I would like to change the colour of each column depending on the value for that column - this will be based on a int target value. For example, if the column is less than our target value, it should display red, else it should display green.

How would you recommend doing this?


Solution

  • I have found a suitable answer for this, the only issue I have with this solution is that the columns come out in varying widths depending on the number of points on the x axis.

        void GetColourCodedSeries(ChartHelper chartHelper, DataTable table, string groupingColumn, string valueColumn)
        {
            List<Color> _palette = new List<Color>();
    
            var x = table.AsEnumerable().Select(f => f.Field<string>(groupingColumn)).ToArray();
    
            foreach (DataRow row in table.Rows)
            {
                if (Convert.ToDecimal(row[valueColumn].ToString()) >= _availabilityTarget) _palette.Add(Color.FromArgb(0, 176, 80));
                else _palette.Add(Color.FromArgb(139, 0, 0));
    
                List<decimal?> y = new List<decimal?>();
    
                foreach(var value in x)
                {
                    if (value == row[groupingColumn].ToString()) y.Add(Convert.ToDecimal(row[valueColumn].ToString()));
                    else y.Add(null);
                }
    
                chartHelper.AddSeries(SeriesChartType.Column, x, y, _palette.ToArray());
            }
        }
    

    This code creates a dynamic colour palette for the columns based on the values. I then add one series per row in my table, when adding the series I am including all of the possible x values and 1 y value per each of these - however, only one of the y axis values has an actual value, all of the others are marked as null values (i did try using 0 values but this made the chart look very messy).