Frequencies: Added the /BARCHART subcommand.
[pspp] / src / output / charts / barchart.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2015 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include "output/charts/barchart.h"
20 #include "output/charts/piechart.h"
21
22 #include <stdlib.h>
23
24 #include "libpspp/cast.h"
25 #include "libpspp/str.h"
26 #include "output/chart-item-provider.h"
27
28 #include "gl/xalloc.h"
29
30 /* Creates and returns a chart that will render a barchart with
31    the given TITLE and the N_BARS described in BARS. */
32 struct chart_item *
33 barchart_create (const char *title, const char *ylabel, const struct slice *bars, int n_bars)
34 {
35   struct barchart *bar;
36   int i;
37
38   bar = xmalloc (sizeof *bar);
39   chart_item_init (&bar->chart_item, &barchart_class, title);
40   bar->bars = xnmalloc (n_bars, sizeof *bar->bars);
41   bar->largest = 0;
42   bar->ylabel = strdup (ylabel);
43   for (i = 0; i < n_bars; i++)
44     {
45       const struct slice *src = &bars[i];
46       struct slice *dst = &bar->bars[i];
47
48       ds_init_string (&dst->label, &src->label);
49       dst->magnitude = src->magnitude;
50       if (dst->magnitude > bar->largest)
51         bar->largest = dst->magnitude;
52     }
53   bar->n_bars = n_bars;
54   return &bar->chart_item;
55 }
56
57 static void
58 barchart_destroy (struct chart_item *chart_item)
59 {
60   struct barchart *bar = to_barchart (chart_item);
61   int i;
62
63   for (i = 0; i < bar->n_bars; i++)
64     {
65       struct slice *slice = &bar->bars[i];
66       ds_destroy (&slice->label);
67     }
68   free (bar->ylabel);
69   free (bar->bars);
70   free (bar);
71 }
72
73 const struct chart_item_class barchart_class =
74   {
75     barchart_destroy
76   };