Recently I was using MSChart control to render different stats. I faced some problems to render TimeStamp on Y axis. Also I realized that it has some properties which are not directly available in intelligence, but are quite useful. So here are some of the problems and tricks/ workaround for those in MSChart Control.
1. Plot Time Stamp / Time Span on Y axis.
I wanted to plot a graph of “response time” for the tasks assigned to the users. I had response time data for each user in seconds. By default MSChart control doesn’t allow you to plot TimeSpan on Y axis. It does allow DateTime but not TimeSpan. One solution to this might be to convert TimeSpan into DateTime format and format chart labels to show data in HH:MM:SS format.
TimeSpan testSpan = TimeSpan.FromSeconds(X);
statsChart.Series(0).Points.AddY(new DateTime(testSpan.Ticks))
statsChart.AxisY.LabelStyle.Format = "hh:mm:ss";
This works fine as long as your timespan doesn’t cross 24 hour. If timespan is more than 24 hours we need to put days as well. Now if you try to print day from the date, problem begins. It tries to add days to date 1/1/1900 and as a result we get dates values from 1/1/1900.
Add Custom Labels
One solution to this problem is plot data points on Y axis as seconds and then customize labels to show seconds in the format dd:hh:mm:ss.
MSChart control supports an event called “Customize” in which we can change the labels of plotted points before they are actually rendered.
if (UserStatsType == StatsType.RespTime)
{
CustomLabelsCollection yAxisLabels = ((Chart)sender).ChartAreas[0].AxisY.CustomLabels;
for (int cnt = 0; cnt < yAxisLabels.Count; cnt++)
{
TimeSpan ts = TimeSpan.FromSeconds(double.Parse(yAxisLabels[cnt].Text));
yAxisLabels[cnt].Text = ts.Days.ToString("00") + ":" + ts.Hours.ToString("00") + ":" + ts.Minutes.ToString("00") + ":" + ts.Seconds.ToString("00");
}
}
2. 3-D effects for Bar Charts
By default bar charts are rendered as plane one color columns. We can make charts attractive by giving 3-D efforts to the charts. MSChart control supports some custom properties. One of them is “DrawingStyle”
foreach (var series in statsChart.Series)
series["DrawingStyle"] = "Cylinder";
Possible values for “DrawingStyle” property are Cylinder, Emboss, LightToDark, Wedge, Default
3. Bar charts with different colors.
By default all data points in a series are plotted in same color. While creating a series, we can set the color of the points. If you want to plot different points with different colors we can set these colors after adding points as follows.
Random rnd = new Random();
foreach (var pt in statsChart.Series[0].Points)
pt.Color = Color.FromArgb((rnd.Next(0, 255)), (rnd.Next(0, 255)), (rnd.Next(0, 255)));