Search code examples
c#windowschartsdata-visualizationaxes

C#, DataVisualization.Charting: assign custom labels to values on axes


In C# I am using the DataVisualization.Charting library for plotting. In a simple line graph, I would like to show some custom text on the x-axis on positions x=0, 1, 2, 3.

Something like this (in matplotlib, though): enter image description here

This is the documentation for Axis class, but I'm not sure what I should look for.


Solution

  • Use the AxisLabel property of DataPoint. Description of AxisLabel property:

    Gets or sets the text of the X-axis label for the data point, series or an empty point. This property is only used if a custom label has not been specified for the relevant Axis object.

    So your code can look like this:

    DataPoint dp1 = new DataPoint(1, 1);
    dp1.AxisLabel = "Frogs";
    DataPoint dp2 = new DataPoint(2, 4);
    dp2.AxisLabel = "Hogs";
    DataPoint dp3 = new DataPoint(3, 9);
    dp3.AxisLabel = "Bogs";
    DataPoint dp4 = new DataPoint(4, 6);
    dp4.AxisLabel = "Slogs";
    chart1.Series[0].Points.Add(dp1);
    chart1.Series[0].Points.Add(dp2);
    chart1.Series[0].Points.Add(dp3);
    chart1.Series[0].Points.Add(dp4);
    

    Or you can enforce 1=Frogs, 2=Hogs, 3=Bogs and 4=Slogs with following code:

    chart1.ChartAreas[0].AxisX.MajorGrid.Enabled = false;
    chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;    
    chart1.Series[0].MarkerStyle = MarkerStyle.Circle;
    chart1.Series[0].MarkerBorderColor = System.Drawing.Color.Black;
    chart1.Series[0].MarkerColor = System.Drawing.Color.Red;
    chart1.Series[0].Points.AddXY(1, 1);
    chart1.Series[0].Points.AddXY(2, 4);
    chart1.Series[0].Points.AddXY(3, 9);
    chart1.Series[0].Points.AddXY(4, 6);
    foreach (DataPoint dp in chart1.Series[0].Points)
    {
        switch ((int)dp.XValue)
        {
            case 1: dp.AxisLabel = "Frogs"; break;
            case 2: dp.AxisLabel = "Hogs"; break;
            case 3: dp.AxisLabel = "Bogs"; break;
            case 4: dp.AxisLabel = "Slogs"; break;
        }
    }
    

    To achieve really the same as on the picture - axes on both sides - you would need to use the following trick.

    It works for X axis only, for Y axis you can add custom labels as described here.

    You can also use labels of datapoints which appear inside the chart using IsValueShownAsLabel.