Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Chart Control axis formatting

I'm using the MS Chart Control in a Winforms app I'm writing. The X-axis component of the scatter plot I'm displaying is Int64 data, which ultimately represents a UTC time. I'd like to take that Int64 data and essentially do a DataTime.FromFileTimeUTC(theTime).ToString() on it to show the end-user X-axis labels that are meaningful.

Currently, I'm creating another column in the in-memory DataTable to hold the DateTime equivalent of that Int64 like so:

dataTable.Columns.Add("mytimestamp");
foreach (DataRow dr in dataTable.Rows)
{
   dr["mytimestamp"] = DateTime.FromFileTimeUTC(Convert.ToInt64(dr["theint64val"].ToString()));
}

And then using the "mytimestamp" column as the x-axis value. This works fine and I can show the x-axis labels as datetime values.

But, I'd rather not go through the trouble of creating the column and essentially duplicating the other column's data but didn't see any way to format the x-axis labels. Might have missed this, I supposed. I saw the AxisViewChanged event in the documentation and saw how I might set the chart title with that data but not the x-axis labels themselves.

Any ideas?

like image 588
itsmatt Avatar asked Oct 20 '09 13:10

itsmatt


2 Answers

I'm very late, but I hope this can be useful for other people...

A possible way to do this is subscribing the chart.FormatNumber event, e.g. :

void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
{
    if (e.ElementType == ChartElementType.AxisLabels &&
        e.ValueType == ChartValueType.Int64)
    {
        e.LocalizedValue = DateTime.FromFileTimeUtc((long)e.Value).ToShortDateString();
    }
}

Since this event handler is called during the conversion of several elements of the chart, to be sure to format only the desired axis, you can pass a custom format to the axis labels:

this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "MyAxisXCustomFormat";

then add a check in the event handler:

void chart1_FormatNumber(object sender, FormatNumberEventArgs e)
{
    if (e.ElementType == ChartElementType.AxisLabels &&
        e.ValueType == ChartValueType.Int64 && 
        e.Format == "MyAxisXCustomFormat")
    {
        e.LocalizedValue = DateTime.FromFileTimeUtc((long)e.Value).ToShortDateString();
    }
}
like image 160
digEmAll Avatar answered Nov 19 '22 00:11

digEmAll


Did you tried to

 yourSeries.XValueType = ChartValueType.Time;
like image 26
Stecya Avatar answered Nov 19 '22 01:11

Stecya