]> git.cworth.org Git - acre/blob - acre.c
Remove code duplication for X and Y ticks
[acre] / acre.c
1 /* acre - A cairo-based library for creating plots and charts.
2  *
3  * Copyright © 2009 Carl Worth <cworth@cworth.org>
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License as
7  * published by the Free Software Foundation; either version 2 of the
8  * License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
18  */
19
20 #define _ISOC99_SOURCE /* for round() */
21 #define _XOPEN_SOURCE 500
22 #define _GNU_SOURCE /* for asprintf() */
23
24 #include "acre.h"
25 #include "xmalloc.h"
26
27 #include <string.h>
28 #include <stdarg.h>
29 #include <math.h>
30
31 typedef struct _acre_data_point_2d {
32     double x;
33     double y;
34 } acre_data_point_2d_t;
35
36 struct _acre_data {
37     char *name;
38
39     acre_data_point_2d_t *points;
40     unsigned int points_size;
41     unsigned int num_points;
42 };
43
44 typedef struct _acre_axis {
45     char *label;
46     double min;
47     double max;
48 } acre_axis_t;
49
50 struct _acre {
51     char *title;
52     acre_axis_t x_axis;
53     acre_axis_t y_axis;
54
55     acre_data_t **data;
56     unsigned int data_size;
57     unsigned int num_data;
58
59     /* Data for drawing. */
60     cairo_t *cr;
61     PangoFontDescription *font;
62
63     /* Total size including labels. */
64     int width;
65     int height;
66
67     /* Position and size of chart alone. */
68     PangoRectangle chart;
69 };
70
71 /* Create a new, empty plot. */
72 acre_t *
73 acre_create (void)
74 {
75     acre_t *acre;
76
77     acre = xmalloc (sizeof (acre_t));
78
79     acre->title = NULL;
80
81     acre->x_axis.label = NULL;
82     acre->x_axis.min = 0.0;
83     acre->x_axis.max = 0.0;
84
85     acre->y_axis.label = NULL;
86     acre->y_axis.min = 0.0;
87     acre->y_axis.max = 0.0;
88
89     acre->data = NULL;
90     acre->data_size = 0;
91     acre->num_data = 0;
92
93     acre->chart.x = 0;
94     acre->chart.y = 0;
95     acre->chart.width = 0;
96     acre->chart.height = 0;
97
98     return acre;
99 }
100
101 /* Destroy a plot. */
102 void
103 acre_destroy (acre_t *acre)
104 {
105     unsigned int i;
106
107     free (acre->title);
108     free (acre->x_axis.label);
109     free (acre->y_axis.label);
110
111     for (i = 0; i < acre->num_data; i++)
112         acre_data_destroy (acre->data[i]);
113
114     free (acre->data);
115
116     free (acre);
117 }
118
119 void
120 acre_set_title (acre_t *acre, const char *title)
121 {
122     free (acre->title);
123
124     acre->title = strdup (title);
125 }
126
127 void
128 acre_set_x_axis_label (acre_t *acre, const char *label)
129 {
130     free (acre->x_axis.label);
131
132     acre->x_axis.label = strdup (label);
133 }
134
135 void
136 acre_set_y_axis_label (acre_t *acre, const char *label)
137 {
138     free (acre->y_axis.label);
139
140     acre->y_axis.label = strdup (label);
141 }
142
143 /* Add a dataset to the plot. The plot assumes ownership of the
144  * dataset so it is not necessary to call acre_data_destroy on it. */
145 void
146 acre_add_data (acre_t *acre, acre_data_t *data)
147 {
148     if (acre->num_data >= acre->data_size) {
149         acre->data_size *= 2;
150         if (acre->data_size == 0)
151             acre->data_size = 1;
152         acre->data = xrealloc_ab (acre->data,
153                                   acre->data_size,
154                                   sizeof (acre_data_t *));
155     }
156
157     acre->data[acre->num_data] = data;
158     acre->num_data++;
159 }
160
161 #define ACRE_FONT_FAMILY "sans"
162 #define ACRE_FONT_SIZE 12
163 #define ACRE_TITLE_FONT_SIZE 32
164 #define ACRE_PAD (ACRE_FONT_SIZE)
165 #define ACRE_TICK_SIZE 6
166 #define ACRE_X_TICK_VALUE_PAD 2
167 #define ACRE_Y_TICK_VALUE_PAD 4
168
169 static PangoLayout *
170 _create_layout (acre_t *acre, const char *text)
171 {
172     PangoLayout *layout;
173
174     layout = pango_cairo_create_layout (acre->cr);
175     pango_layout_set_font_description (layout, acre->font);
176     pango_layout_set_text (layout, text, -1);
177     pango_layout_set_alignment (layout, PANGO_ALIGN_CENTER);
178
179     return layout;
180 }
181
182 #define PRINTF_FORMAT(fmt_index, va_index) __attribute__ ((__format__(__printf__, fmt_index, va_index)))
183
184 static PangoLayout *
185 _create_layout_vprintf (acre_t *acre, const char *fmt, va_list ap)
186 {
187     PangoLayout *layout;
188     char *text;
189
190     vasprintf (&text, fmt, ap);
191
192     layout = _create_layout (acre, text);
193
194     free (text);
195
196     return layout;
197 }
198
199 static PangoLayout *
200 _create_layout_printf (acre_t *acre, const char *fmt, ...)
201     PRINTF_FORMAT (2, 3);
202
203 static PangoLayout *
204 _create_layout_printf (acre_t *acre, const char *fmt, ...)
205 {
206     va_list ap;
207     PangoLayout *layout;
208
209     va_start (ap, fmt);
210
211     layout = _create_layout_vprintf (acre, fmt, ap);
212
213     va_end (ap);
214
215     return layout;
216 }
217
218 static void
219 _destroy_layout (PangoLayout *layout)
220 {
221     g_object_unref (layout);
222 }
223
224 static void
225 _show_layout (cairo_t *cr, PangoLayout *layout)
226 {
227     pango_cairo_show_layout (cr, layout);
228
229     _destroy_layout (layout);
230 }
231
232 static void
233 _draw_title_and_labels (acre_t *acre)
234 {
235     cairo_t *cr = acre->cr;
236     PangoFontDescription *title_font;
237     PangoLayout *title_layout, *x_axis_layout, *y_axis_layout;
238     PangoLayout *min_y, *max_y;
239     int min_y_width, max_y_width, y_axis_value_width;
240     int title_width, title_height;
241     int x_axis_width, x_axis_height;
242     int y_axis_width, y_axis_height;
243     PangoRectangle new_chart;
244
245     cairo_save (cr);
246
247     acre->font = pango_font_description_new ();
248     pango_font_description_set_family (acre->font, ACRE_FONT_FAMILY);
249     pango_font_description_set_absolute_size (acre->font,
250                                               ACRE_FONT_SIZE * PANGO_SCALE);
251
252     title_font = pango_font_description_new ();
253     pango_font_description_set_family (title_font, ACRE_FONT_FAMILY);
254     pango_font_description_set_absolute_size (title_font,
255                                               ACRE_TITLE_FONT_SIZE * PANGO_SCALE);
256
257     title_layout = _create_layout (acre, acre->title);
258     pango_layout_set_font_description (title_layout, title_font);
259
260     x_axis_layout = _create_layout (acre, acre->x_axis.label);
261     y_axis_layout = _create_layout (acre, acre->y_axis.label);
262
263     min_y = _create_layout_printf (acre, "%g",
264                                    round (acre->y_axis.min));
265     max_y = _create_layout_printf (acre, "%g",
266                                    round (acre->y_axis.max));
267
268     pango_layout_get_pixel_size (min_y, &min_y_width, NULL);
269     pango_layout_get_pixel_size (max_y, &max_y_width, NULL);
270     y_axis_value_width = MAX (min_y_width, max_y_width);
271
272     _destroy_layout (min_y);
273     _destroy_layout (max_y);
274
275     /* Iterate with the layout of the title and axis labels until they
276      * are stable, (this requires iteration since we don't know what
277      * to set their widths to in advance due to the wrapping of the
278      * other elements). */
279     while (1) {
280         pango_layout_set_width (title_layout, acre->chart.width * PANGO_SCALE);
281         pango_layout_set_width (x_axis_layout, acre->chart.width * PANGO_SCALE);
282         pango_layout_set_width (y_axis_layout, acre->chart.height * PANGO_SCALE);
283
284         pango_layout_get_pixel_size (title_layout, &title_width, &title_height);
285         pango_layout_get_pixel_size (x_axis_layout, &x_axis_width, &x_axis_height);
286         pango_layout_get_pixel_size (y_axis_layout, &y_axis_width, &y_axis_height);
287
288         new_chart.x = ACRE_PAD + y_axis_height +
289             ACRE_PAD + y_axis_value_width + ACRE_Y_TICK_VALUE_PAD;
290         new_chart.width = acre->width - acre->chart.x - ACRE_PAD;
291
292         new_chart.y = ACRE_PAD + title_height + ACRE_PAD;
293         new_chart.height = acre->height - acre->chart.y - 
294             (ACRE_X_TICK_VALUE_PAD + ACRE_FONT_SIZE +
295              ACRE_PAD + x_axis_height + ACRE_PAD);
296
297         if (new_chart.x == acre->chart.x &&
298             new_chart.y == acre->chart.y &&
299             new_chart.width == acre->chart.width &&
300             new_chart.height == acre->chart.height)
301         {
302             break;
303         }
304
305         acre->chart.x = new_chart.x;
306         acre->chart.y = new_chart.y;
307         acre->chart.width = new_chart.width;
308         acre->chart.height = new_chart.height;
309     }
310
311     cairo_set_source_rgb (cr, 0, 0, 0);
312
313     cairo_move_to (cr, acre->chart.x, ACRE_PAD);
314     _show_layout (cr, title_layout);
315
316     cairo_save (cr);
317     {
318         cairo_translate (cr, ACRE_PAD, acre->chart.y + acre->chart.height);
319         cairo_rotate (cr, - M_PI / 2.0);
320         cairo_move_to (cr, 0, 0);
321         _show_layout (cr, y_axis_layout);
322     }
323     cairo_restore (cr);
324
325     cairo_move_to (cr, acre->chart.x,
326                    acre->chart.y + acre->chart.height +
327                    ACRE_FONT_SIZE + ACRE_PAD);
328     _show_layout (cr, x_axis_layout);
329
330     cairo_restore (cr);
331 }
332
333 /* For a given axis range, compute a step size (in data space) to
334  * generate a suitable number of ticks (5 or so). */
335 static double
336 _step_for_range (double range)
337 {
338     double step, scale_factor;
339
340     /* We want roughly 5 major ticks for the chart. */
341     step = range / 5;
342
343     /* Normalize the step so we can easily snap it to a desirable
344      * value. */
345     scale_factor = pow (10.0, floor (log10 (step)));
346     step /= scale_factor;
347
348     /* We want increments of 1, 2.5, 5, or 10 (times some power of
349      * 10). The threshold values between these are computed
350      * logarithmically. */
351     if (step < 3.535533905932738) {
352         if (step < 1.58113883008419)
353             step = 1.0;
354         else
355             step = 2.5;
356     } else {
357         if (step < 7.071067811865475)
358             step = 5.0;
359         else
360             step = 10.0;
361     }
362
363     /* Un-normalize and we now have the data value that we want to
364      * step at. */
365     return step * scale_factor;
366 }
367
368 /* Given an axis range, we can compute a desired data-space step
369  * amount for the major ticks (see _step_for_range). To get
370  * nice-looking pixel-snapped ticks we want to expand the range
371  * slightly. */
372 static void
373 _expand_range_for_width (double *axis_min, double *axis_max, int pixel_size)
374 {
375     double range, new_range, step, pixel_step;
376
377     range = *axis_max - *axis_min;
378
379     step = _step_for_range (range);
380     pixel_step = step * pixel_size / range;
381
382     /* We expand the range by the ratio of the pixel step to the floor
383      * of the pixel_step.
384      */
385     new_range = range * pixel_step / floor (pixel_step);
386
387     /* And spread the increase out on either side of the range. */
388     *axis_min -= (new_range - range) / 2.0;
389     *axis_max += (new_range - range) / 2.0;
390 }
391
392 /* Setup a transformation in acre->cr such that data values plotted
393  * will appear where they should within the chart.
394  */
395 static void
396 _set_transform_to_data_space (acre_t *acre)
397 {
398     cairo_t *cr = acre->cr;
399
400     cairo_translate (cr,
401                      acre->chart.x,
402                      acre->chart.y + acre->chart.height);
403     cairo_scale (cr,
404                  acre->chart.width / (acre->x_axis.max - acre->x_axis.min),
405                  - acre->chart.height /(acre->y_axis.max - acre->y_axis.min));
406     cairo_translate (cr, -acre->x_axis.min, -acre->y_axis.min);
407 }
408
409 static void
410 _compute_axis_ranges (acre_t *acre)
411 {
412     unsigned int d, i;
413     acre_data_t *data;
414     double x_adjust, y_adjust;
415     cairo_t *cr = acre->cr;
416
417     acre->x_axis.min = acre->data[0]->points[0].x;
418     acre->x_axis.max = acre->data[0]->points[0].x;
419     acre->y_axis.min = acre->data[0]->points[0].y;
420     acre->y_axis.min = acre->data[0]->points[0].y;
421
422     /* First, simply find the extrema of the data. */
423     for (d = 0; d < acre->num_data; d++) {
424         data = acre->data[d];
425         for (i = 0; i < data->num_points; i++) {
426             if (data->points[i].x < acre->x_axis.min)
427                 acre->x_axis.min = data->points[i].x;
428             if (data->points[i].x > acre->x_axis.max)
429                 acre->x_axis.max = data->points[i].x;
430
431             if (data->points[i].y < acre->y_axis.min)
432                 acre->y_axis.min = data->points[i].y;
433             if (data->points[i].y > acre->y_axis.max)
434                 acre->y_axis.max = data->points[i].y;
435         }
436     }
437
438     /* Next, increase the axis ranges just enough so that the step
439      * sizes for the ticks will be integers.
440      */
441     _expand_range_for_width (&acre->x_axis.min,
442                              &acre->x_axis.max,
443                              acre->chart.width);
444
445     _expand_range_for_width (&acre->y_axis.min,
446                              &acre->y_axis.max,
447                              acre->chart.height);
448
449     /* Finally, we also translate the axis ranges slightly so that the
450      * ticks land on half-integer device-pixel positions.
451      */
452     cairo_save (cr);
453     {
454         _set_transform_to_data_space (acre);
455
456         x_adjust = 0.0;
457         y_adjust = 0.0;
458         cairo_user_to_device (cr, &x_adjust, &y_adjust);
459         x_adjust = (round (x_adjust + 0.5) - 0.5) - x_adjust;
460         y_adjust = (round (y_adjust + 0.5) - 0.5) - y_adjust;
461         cairo_device_to_user_distance (cr, &x_adjust, &y_adjust);
462
463         acre->x_axis.min -= x_adjust;
464         acre->x_axis.max -= x_adjust;
465
466         acre->y_axis.min -= y_adjust;
467         acre->y_axis.max -= y_adjust;
468     }
469     cairo_restore (cr);
470 }
471
472 static void
473 _draw_data (acre_t *acre)
474 {
475     cairo_t *cr = acre->cr;
476     unsigned int d, i;
477     acre_data_t *data;
478
479     cairo_save (cr);
480
481     cairo_set_source_rgb (cr, 0, 0, 0);
482
483     _set_transform_to_data_space (acre);
484
485     for (d = 0; d < acre->num_data; d++) {
486         data = acre->data[d];
487         cairo_new_path (cr);
488         for (i = 0; i < data->num_points; i++) {
489             cairo_line_to (cr,
490                            data->points[i].x,
491                            data->points[i].y);
492         }
493         cairo_save (cr);
494         {
495             cairo_identity_matrix (cr);
496             cairo_set_line_width (cr, 1.0);
497             cairo_stroke (cr);
498         }
499         cairo_restore (cr);
500     }
501
502     cairo_restore (cr);
503 }
504
505 typedef enum _ticks { ACRE_TICKS_X, ACRE_TICKS_Y } acre_ticks_t;
506
507 static void
508 _draw_ticks (acre_t *acre,
509              double axis_min, double axis_max,
510              acre_ticks_t ticks)
511 {
512     cairo_t *cr = acre->cr;
513     double i, step;
514
515     cairo_save (cr);
516
517     _set_transform_to_data_space (acre);
518
519     step = _step_for_range (axis_max - axis_min);
520     i = (floor (axis_min / step) + 1) * step;
521
522     while (i <= axis_max) {
523         if (ticks == ACRE_TICKS_X)
524             cairo_move_to (cr, i, acre->y_axis.min);
525         else
526             cairo_move_to (cr, acre->x_axis.min, i);
527
528         /* tick */
529         cairo_save (cr);
530         {
531             cairo_identity_matrix (cr);
532             if (ticks == ACRE_TICKS_X) {
533                 cairo_rel_line_to (cr, 0, 0.5);
534                 cairo_rel_line_to (cr, 0, -ACRE_TICK_SIZE-0.5);
535             } else {
536                 cairo_rel_line_to (cr, -0.5, 0);
537                 cairo_rel_line_to (cr, ACRE_TICK_SIZE+0.5, 0);
538             }
539             cairo_set_line_width (cr, 1.0);
540             cairo_stroke (cr);
541         }
542         cairo_restore (cr);
543
544         /* label */
545         cairo_save (cr);
546         {
547             PangoLayout *layout;
548             int width, height;
549
550             layout = _create_layout_printf (acre, "%g", i);
551
552             if (ticks == ACRE_TICKS_X)
553                 cairo_move_to (cr, i, acre->y_axis.min);
554             else
555                 cairo_move_to (cr, acre->x_axis.min, i);
556
557             cairo_identity_matrix (cr);
558             pango_layout_get_pixel_size (layout, &width, &height);
559
560             if (ticks == ACRE_TICKS_X)
561                 cairo_rel_move_to (cr, -width / 2, ACRE_X_TICK_VALUE_PAD);
562             else
563                 cairo_rel_move_to (cr, -width - ACRE_Y_TICK_VALUE_PAD,
564                                    -height/2);
565
566             _show_layout (cr, layout);
567         }
568         cairo_restore (cr);
569
570         i += step;
571     }
572
573     cairo_restore (cr);
574 }
575
576 static void
577 _draw_frame_and_ticks (acre_t *acre)
578 {
579     cairo_t *cr = acre->cr;
580
581     cairo_save (cr);
582
583     cairo_set_source_rgb (cr, 0, 0, 0); /* black */
584
585     /* ticks */
586     _draw_ticks (acre, acre->x_axis.min, acre->x_axis.max, ACRE_TICKS_X);
587     _draw_ticks (acre, acre->y_axis.min, acre->y_axis.max, ACRE_TICKS_Y);
588
589     /* frame */
590     cairo_rectangle (cr,
591                      acre->chart.x - 0.5, acre->chart.y - 0.5,
592                      acre->chart.width + 1.0, acre->chart.height + 1.0);
593     cairo_set_line_width (cr, 1.0);
594     cairo_stroke (cr);
595
596     cairo_restore (cr);
597 }
598
599 /* Draw the plot to the given cairo context within a user-space
600  * rectangle from (0, 0) to (width, height). This size includes all
601  * space for extra-plot elements (such as the title, the axis labels,
602  * etc.)
603  */
604 void
605 acre_draw (acre_t *acre, cairo_t *cr, int width, int height)
606 {
607     acre->cr = cr;
608
609     acre->width = width;
610     acre->height = height;
611
612     acre->chart.width = width;
613     acre->chart.height = height;
614
615     cairo_save (cr);
616
617     cairo_set_source_rgb (cr, 1, 1, 1);
618
619     /* We compute the axis ranges before doing label layout so that we
620      * can account for the width of the y-axis value labels. */
621     _compute_axis_ranges (acre);
622
623     _draw_title_and_labels (acre);
624
625     /* And we recompute the axis ranges now that the title and axis
626      * label space is all measured and accounted for. */
627     _compute_axis_ranges (acre);
628
629     _draw_data (acre);
630
631     _draw_frame_and_ticks (acre);
632 }
633
634 /* Create a new dataset---a collection of (x, y) datapoints. A single
635  * plot can contain multiple datasets, (see acre_add_data). */
636 acre_data_t *
637 acre_data_create (void)
638 {
639     acre_data_t *data;
640
641     data = xmalloc (sizeof (acre_data_t));
642
643     data->name = NULL;
644
645     data->points = NULL;
646     data->points_size = 0;
647     data->num_points = 0;
648
649     return data;
650 }
651
652 /* Destroy an acre dataset. Do not call this function if the dataset
653  * has been added to an acre_t plot with acre_add_data. */
654 void
655 acre_data_destroy (acre_data_t *data)
656 {
657     free (data->points);
658
659     free (data);
660 }
661
662 /* Set the label for this dataset (to appear in the plot's key). */
663 void
664 acre_data_set_name (acre_data_t *data, const char *name)
665 {
666     free (data->name);
667
668     data->name = strdup (name);
669 }
670
671 /* Add a datapoint to the given dataset. */
672 void
673 acre_data_add_point_2d (acre_data_t *data, double x, double y)
674 {
675     if (data->num_points >= data->points_size) {
676         data->points_size *= 2;
677         if (data->points_size == 0)
678             data->points_size = 16;
679         data->points = xrealloc_ab (data->points,
680                                     data->points_size,
681                                     sizeof (acre_data_point_2d_t));
682     }
683
684     data->points[data->num_points].x = x;
685     data->points[data->num_points].y = y;
686     data->num_points++;
687 }