ckplot

Unnamed repository
Log | Files | Refs

commit c6adc9093fb429480d8a752308eac1b626f45957
Author: aabacchus <ben@bvnf.space>
Date:   Sun,  3 Oct 2021 00:26:03 +0100

kplot: plot scatter graphs using kplot(3) and csv(3)

Diffstat:
A.gitignore | 3+++
AMakefile | 12++++++++++++
Akplot.c | 87+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
3 files changed, 102 insertions(+), 0 deletions(-)

diff --git a/.gitignore b/.gitignore @@ -0,0 +1,3 @@ +kplot +*.pdf +*.csv diff --git a/Makefile b/Makefile @@ -0,0 +1,12 @@ +.POSIX: + +XCFLAGS = $(CFLAGS) -I/usr/local/include -I/usr/include/cairo -Wall -Wextra -Wpedantic +XLDFLAGS = $(LDFLAGS) -lkplot -L/usr/local/lib -lcsv -lcairo + +kplot: kplot.c + $(CC) $(XCFLAGS) $(XLDFLAGS) -o $@ $< + +clean: + rm -f kplot + +.PHONY: clean diff --git a/kplot.c b/kplot.c @@ -0,0 +1,87 @@ +#include <bsd/stdio.h> +#include <bsd/stdlib.h> +#include <cairo.h> +#include <cairo-pdf.h> +#include <csv.h> +#include <kplot.h> +#include <math.h> +#include <unistd.h> + +void +usage(char *argv0) { + fprintf(stderr, "usage: %s [-H] file.csv\n", argv0); + fprintf(stderr, " -H treat first line as header\n"); +} + +int +main(int argc, char **argv) { + int ch, flag_H; + flag_H = 0; + while ((ch = getopt(argc, argv, "H")) != -1) { + switch (ch) { + case 'H': + flag_H = 1; + break; + case '?': + usage(*argv); + return 1; + } + } + + if (argc - optind == 0) { + usage(*argv); + return 1; + } + + argv += optind; + + FILE *f = fopen(*argv, "r"); + if (f == NULL) { + perror(*argv); + return 1; + } + + struct csv *c = csv_create(); + if (csv_read_file(f, c, flag_H) != 0) { + perror("csv_read_file"); + return 1; + } + if (c->cols != 2) { + fprintf(stderr, "%d columns - what should be plotted?\n", c->cols); + csv_destroy(c); + return 1; + } + if (c->rows < 1) { + fprintf(stderr, "no rows found\n"); + csv_destroy(c); + return 1; + } + + int rows = c->rows; + struct kpair points1[c->rows]; + + for (int i = 0; i < c->rows; i++) { + points1[i].x = c->data[i][0]; + points1[i].y = c->data[i][1]; + } + csv_destroy(c); + + struct kdata *d1; + struct kplot *p; + cairo_surface_t *surf; + cairo_t *cr; + + d1 = kdata_array_alloc(points1, rows); + p = kplot_alloc(NULL); + kplot_attach_data(p, d1, KPLOT_POINTS, NULL); + kdata_destroy(d1); + //surf = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 600, 400); + surf = cairo_pdf_surface_create("out.pdf", 600, 400); + cr = cairo_create(surf); + cairo_surface_destroy(surf); + kplot_draw(p, 600.0, 400.0, cr); + //cairo_surface_write_to_png(cairo_get_target(cr), "example0.png"); + cairo_destroy(cr); + kplot_free(p); + return 0; +}