This is just so that I can refer to some example code when I tell people to use gnuplot (instead of for example the popular GD module) to draw plots.

use strict; use warnings; use 5.010; use IO::Handle; use File::Temp "tempfile"; my($T,$N) = tempfile("plot-XXXXXXXX", "UNLINK", 1); for my $t (100..500) { say $T $t*sin($t*0.1), " ", $t*cos($t*0.1); } close $T; open my $P, "|-", "gnuplot" or die; printflush $P qq[ unset key plot "$N" with lines lw 3 ]; <STDIN>; close $P; __END__

You need gnuplot installed on your computer to run this. Read the gnuplot manual if you want to control the plot, for example change its appeariance, use dates as one coordinate, or export the plot to an image file. Use empty lines to draw discontinuous line segments.

Update: other posts where I've recommended gnuplot are: Re: perl postscript, Re: Interface to Gnuplot ?, Re^2: Easy plotting ?, Re^3: measuring IN/OUT traffic on your computer, Re: Draw chart (recommended), Re: Matrix magic with Perl + Octave, R or MatLab?, Re: parse a csv file and create array of arrays and then plot the data, Re: Export Plots, Two questions for GD::Graph, Stacked Bar (recommended).

Update: see also other posts about gnuplot: Statistical Graphs with gnuplot and mod_perl, Chart::Gnuplot png format, Re: Intro to plotting with perl.

Update 2011-01-28: added the statement close $T; which fixes a possible bug where the handle $T is not flushed.

Replies are listed 'Best First'.
Re: Plot a spiral with gnuplot
by RichardK (Parson) on Aug 16, 2011 at 11:51 UTC

    When I use gnuplot I use its special file handle '-' and inline the data.

    Would it be better to use a tempfile? and if so what are the advantages?

    I'd write your code like this :-

    use v5.12; use warnings; use autodie; use IO::Handle; open my $out,'|-','gnuplot'; say $out 'unset key'; say $out "plot '-' with lines lw 3"; for my $t (100..500) { say $out $t*sin($t*0.1),' ',$t*cos($t*0.1); } say $out 'e'; flush $out; <STDIN>; close $out;

      Frankly, I didn't know you could give gnuplot data inline like that. The manual of gnuplot is a bit long and boring, so I've read only a little of it. Thank you for telling about this.