A.bakker
A.bakker

Reputation: 231

Winform Chart with the X axis label being between 2 hours

I have a Datatable connected to a chart. The datatable is simply two columns, Number and DateTime. Seeing 1440 possible columns in a chart is a bit excessive i decided to strip away the minutes (rounding the time down to the hour, so 14:20 will become 14:00). The problem with this is that the Label just shows 14. I want it to show 14-15, 15-16, 16-17 as in indication that the number belongs between those points in time.

This is what i am currently using:

chart1.ChartAreas["ChartArea1"].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Format = "HH";

Is there away to alter the label in such away that it would be something like HH + (HH+1)?

Also as a bit of a bonus question, would it also be possible to make the DateTimeInterval half an hour instead of a full hour (14:00- 14:30, 14:30-15:00 and so on)?

Upvotes: 0

Views: 348

Answers (1)

TnTinMn
TnTinMn

Reputation: 11801

You can use the Chart.FormatNumber Event to override the presented axis label to display whatever string you want.

using System;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        private Random rnd = new Random();

        public Form1()
        {
            InitializeComponent();
            SetupChart();
        }

        private void SetupChart()
        {
            chart1.Series.Clear();
            chart1.Legends.Clear();

            ChartArea area = chart1.ChartAreas[0];
            area.AxisX.IntervalType = DateTimeIntervalType.Hours;
            area.AxisX.LabelStyle.Format = "HH";
            area.AxisX.Interval = 1.0D;

            Series s = new Series("TimeData");
            s.ChartType = SeriesChartType.Point;
            s.ChartArea = area.Name;
            s.XValueType = ChartValueType.DateTime;
            s.YValueType = ChartValueType.Int32;

            DateTime t = DateTime.Today;

            TimeSpan timeIncrement = new TimeSpan(0, 15, 0);

            for (Int32 i = 0; i <= 19; i++)
            {
                s.Points.AddXY(t, rnd.Next(5, 16));
                t = t.Add(timeIncrement);
            }

            chart1.Series.Add(s);
            chart1.FormatNumber += chart1_FormatNumber;

        }


        private void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
        {
            if (e.ElementType == ChartElementType.AxisLabels  && sender == chart1.ChartAreas[0].AxisX)
            {
                DateTime d1 = DateTime.FromOADate(e.Value);
                DateTime d2 = d1.AddHours(1);
                e.LocalizedValue = $"{d1:HH}-{d2:HH}";
            }
        }

    }
}

Upvotes: 1

Related Questions