Plot x, y arrays

From Rosetta Code

Jump to: navigation, search

Programming Task
This is a programming task. It lays out a problem which Rosetta Code users are encouraged to solve, using languages they know.

Code examples should be formatted along the lines of one of the existing prototypes.

Plot a function represented as `x', `y' numerical arrays.

Post link to your resulting image for input arrays (see Example section for Python language on Query Performance page):

x = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
y = {2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0};

This task is intended as a subtask for Measure relative performance of sorting algorithms implementations.

Contents

[edit] J

Library: plot

   load 'plot'
   magnitudes =: 2.7 2.8 31.4 38.1 58.0 76.2 100.5 130.0 149.3 180.0
   'dot; pensize 2.4' plot magnitudes

Output of plot.

[edit] Maxima

(%i1) ".." (m, n) := makelist (i, i, m, n); infix ("..")$
(%i2) x: 0 .. 9$ y:[2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]$
(%i3) plot2d(['discrete, x, y], [style, [points,5,1,1]], [gnuplot_term, png], [gnuplot_out_file, "qsort-range-10-9.png"])$

qsort-range-10-9.png

[edit] OCaml

#load "graphics.cma"
open Graphics
 
let round x = int_of_float (floor(x +. 0.5))
 
let x = [0; 1; 2; 3; 4; 5; 6; 7; 8; 9]
and y = [2.7; 2.8; 31.4; 38.1; 58.0; 76.2; 100.5; 130.0; 149.3; 180.0]
 
let () =
  open_graph "";
  List.iter2
    (fun x y ->
      (* scale to fit in the window *)
      let _x = x * 30
      and _y = round(y *. 2.0) in
      plot _x _y)
    x y;
  ignore(wait_next_event [Key_pressed]);
  close_graph();
;;

[edit] Perl

Library: GD::Graph

 
 use GD::Graph::points;
 
 @data = (
   [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
   [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0],
 );
 $graph = GD::Graph::points->new(400, 300);
 $gd = $graph->plot(\@data) or die $graph->error;
 
 # Save as image.
 open(OUF, ">qsort-range-10-9.png");
 binmode OUF;
 print OUF $gd->png;
 close(OUF);
 

Library: Imager

Library: Imager::Plot

 
 use Imager;
 use Imager::Plot;
 
 @x = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
 @y = (2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0);
 $plot = Imager::Plot->new(
   'Width' => 400,
   'Height' => 300,
   'GlobalFont' => 'PATH_TO_TTF_FONT',
 );
 $plot->AddDataSet(
   'X' => \@x,
   'Y' => \@y,
   'style' => {
     'marker' => {
       'size' => 2,
       'symbol' => 'circle',
       'color' => Imager::Color->new('red'),
     },
   },
 );
 $img = Imager->new(
   'xsize' => 500,
   'ysize' => 400,
 );
 $img->box('filled' => 1, 'color' => 'white');
 $plot->Render('Image' => $img, 'Xoff' => 50, 'Yoff' => 350);
 $img->write('file' => 'qsort-range-10-9.png');
 

[edit] Python

Library: matplotlib

>>> x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> y = [2.7, 2.8, 31.4, 38.1, 58.0, 76.2, 100.5, 130.0, 149.3, 180.0]
>>> import pylab
>>> pylab.plot(x, y, 'bo')
>>> pylab.savefig('qsort-range-10-9.png')

qsort-range-10-9.png (23 KiB)

Personal tools