A better than CPTTimeFormatter to show dates on an axis

484 views
Skip to first unread message

Craig Hockenberry

unread,
Mar 2, 2012, 5:24:54 PM3/2/12
to coreplot-discuss
Two issues:

1) Bar plots don't respect the majorIntervalLength when plotting --
the bars are always placed on integral units. So a trick like setting
the interval to 24*60*60 to display daily values won't work.

2) Changing the x scale just to make CPTTimeFormatter happy is counter-
intuitive. The "oneDay" constants in the Plot Gallery app proves
this :-)

When you're plotting time intervals, you have a priori knowledge of
the date range you're working with. Applying this knowledge to the
axes is wrong, in my opinion. It makes more sense to apply that
knowledge to the formatter itself.

I've created a CPTCalendarFormatter class that you can use like this
to display daily data along the x axis:

CPTXYAxis *x = axisSet.xAxis;
{
x.majorIntervalLength = CPTDecimalFromInteger(1);

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init]
autorelease];
dateFormatter.dateStyle = kCFDateFormatterShortStyle;
CPTCalendarFormatter *calendarFormatter = [[[CPTCalendarFormatter
alloc] initWithDateFormatter:dateFormatter] autorelease];
calendarFormatter.referenceDate = [NSDate date];
calendarFormatter.referenceCalendarUnit = NSDayCalendarUnit;
x.labelFormatter = calendarFormatter;
}

If you're working with months or years, it's just a matter of changing
to NSMonthCalendarUnit or NSYearCalendarUnit.

I'm not going to learn Mecurial just to add this to the project, so
you can download the code from here:

http://files.iconfactory.net/craig/whatever/CPTCalendarFormatter.zip

Enjoy!

Eric

unread,
Mar 2, 2012, 10:03:35 PM3/2/12
to coreplot...@googlegroups.com
Craig,

Do you mind if we pull this class into Core Plot? I won't have time to do it for a week or so, but maybe Drew or one of the other maintainers could do it sooner.

Thanks,
Eric

Teresa Van Dusen

unread,
Mar 2, 2012, 10:10:31 PM3/2/12
to coreplot...@googlegroups.com
Thanks for the code Craig. I'll use it in my project if you don't mind.

Craig Hockenberry

unread,
Mar 3, 2012, 1:32:09 PM3/3/12
to coreplot-discuss
Yes, please use it by all means. I followed the coding standards used
by the project, so there shouldn't be any issues.

-ch

Eric

unread,
Mar 21, 2012, 9:38:00 PM3/21/12
to coreplot...@googlegroups.com
CPTCalendarFormatter is now part of Core Plot. Thanks, Craig!

Eric
Reply all
Reply to author
Forward
0 new messages