* Not ideal, but it is functional.
[scdataviz] / graph.c
diff --git a/graph.c b/graph.c
index 507e557..df419b9 100644 (file)
--- a/graph.c
+++ b/graph.c
@@ -32,6 +32,11 @@ along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #include <graph.h>
 #include <stdlib.h>
 #include <stdio.h>
+#include <math.h>
+
+#ifdef DEBUG
+#define DEBUG_AUTOAXIS
+#endif
 
 G_DEFINE_TYPE(Graph, graph, G_TYPE_OBJECT);
 
@@ -175,18 +180,55 @@ void graph_set_yaxis(Graph *g, struct graph_axis *axis) {
   g->yaxis=axis;
 }
 
-void graph_autoset_xaxis(Graph *g) {
+struct graph_axis* autoset_axis(Graph* g, GString* title, double min, double max) {
   struct graph_axis *axis;
+  double range_mag;
+  double start_mag;
+  double stop_mag;
+  if(g->points->len == 0) {
+    return NULL;
+  }
   if((axis=(struct graph_axis *)malloc(sizeof(struct graph_axis))) == NULL) {
-    return 1;
+    return NULL;
+  }
+  if(g->points->len == 1) {
+    axis->major=1;
+    axis->minor=0;
+    axis->subminor=0;
+    axis->major_start=min;
+    axis->major_step=max;
+  }else{
+    range_mag = logb(max - min);
+    if(min == 0) 
+      start_mag = 0;
+    else
+      start_mag = copysign(pow(10, floor(log10(min))), min);
+    if(max == 0) 
+      stop_mag = 0;
+    else
+      stop_mag = copysign(pow(10, ceil(log10(max))), max);
+    if(stop_mag == start_mag) stop_mag *= 10;
+    axis->major=10;
+    axis->minor=0;
+    axis->subminor=0;
+    axis->major_start=start_mag;
+    axis->major_step=(stop_mag - start_mag)/(axis->major);
   }
-  graph_set_xaxis(g, axis);
+  axis->title=g_string_new(title->str);
+  #ifdef DEBUG_AUTOAXIS
+  fprintf(stderr, "graph_autoset_xaxis: xmin=%g, log10(xmin)=%g, floor=%g, pow=%g round=%g\n", min, log10(min), floor(log10(min)), pow(10, floor(log10(min))), round(pow(10, floor(log10(min)))));
+  fprintf(stderr, "graph_autoset_xaxis: xmax=%g, log10(xmax)=%g, floor=%g, pow=%g round=%g\n", max, log10(max), floor(log10(max)), pow(10, floor(log10(max))), round(pow(10, floor(log10(max)))));
+  fprintf(stderr, "graph_autoset_xaxis: xmin=%g,max=%g start_mag=%g, stop_mag=%g range_mag=%g\n", min, max, start_mag, stop_mag, range_mag);
+  #endif
+  return axis;
 }
 
-void graph_autoset_yaxis(Graph *g) {
-  struct graph_axis *axis;
-  if((axis=(struct graph_axis *)malloc(sizeof(struct graph_axis))) == NULL) {
-    return 1;
-  }
-  graph_set_xaxis(g, axis);
+int graph_autoset_xaxis(Graph *g, GString *title) {
+  graph_set_xaxis(g, autoset_axis(g, title, g->minx, g->maxx));
+  return 0;
+}
+
+int graph_autoset_yaxis(Graph *g, GString *title) {
+  graph_set_yaxis(g, autoset_axis(g, title, g->miny, g->maxy));
+  return 0;
 }