blib/lib/PDL/Graphics/Prima/Simple.pm untested

filter: Statementstmt 0.0% 0 / 145 Branchbran 0.0% 0 / 52 Conditioncond 0.0% 0 / 24 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 16 totaltotal 0.0% 0 / 261 CC 22 SCAR 28.0
CC
22
Cov
0%
default_plot
56.0
hist_plot
20.0
import
20.0
CRAP 16.4
1 package PDL::Graphics::Prima::Simple;
2 use strict;
3 use warnings;
4 use Carp 'croak';
5  
6 our $VERSION = 0.17; # update with update-version.pl
7  
8 use PDL::Graphics::Prima;
9  
10 =head1 NAME
11  
12 PDL::Graphics::Prima::Simple - a very simple plotting interface for
13 PDL::Graphics::Prima
14  
15 =head1 SYNOPSIS
16  
17 use PDL::Graphics::Prima::Simple;
18 use PDL;
19
20
21 # --( Super simple line and symbol plots )--
22
23 # Generate some data - a sine curve
24 my $x = sequence(100) / 20;
25 my $y = sin($x);
26
27 # Draw x/y pairs. Default x-value are sequential:
28 line_plot($y); line_plot($x, $y);
29 circle_plot($y); circle_plot($x, $y);
30 triangle_plot($y); triangle_plot($x, $y);
31 square_plot($y); square_plot($x, $y);
32 diamond_plot($y); diamond_plot($x, $y);
33 X_plot($y); X_plot($x, $y);
34 cross_plot($y); cross_plot($x, $y);
35 asterisk_plot($y); asterisk_plot($x, $y);
36
37 # Sketch the sine function for x initially from 0 to 10:
38 func_plot(0 => 10, \&PDL::sin);
39
40
41 # --( Super simple histogram )--
42
43 # Plot a distribution
44 hist_plot($distribution);
45 # Tweak the binning
46 hist_plot($distribution, bt::Linear(normalize => 0));
47
48
49 # --( Super simple matrix plots )--
50
51 # Generate some data - a wavy pattern
52 my $image = sin(sequence(100)/10)
53 + sin(sequence(100)/20)->transpose;
54
55 # Generate a grayscale image:
56 matrix_plot($image); # smallest is white
57 imag_plot($image); # smallest is black
58
59 # Set the x and y coordinates for the image boundaries
60 # left, right, bottom, top
61 matrix_plot([ 0, 1 ], [ 0, 2 ], $image);
62 imag_plot( [ 0, 1 ], [ 0, 2 ], $image);
63
64
65 # --( More complex plots )--
66
67 # Use the more general 'plot' function for
68 # multiple DataSets and more plotting features:
69 my $colors = pal::Rainbow()->apply($x);
70 plot(
71 -lines => ds::Pair($x, $y
72 , plotType => ppair::Lines
73 ),
74 -color_squares => ds::Pair($x, $y + 1
75 , colors => $colors,
76 , plotType => ppair::Squares(filled => 1)
77 ),
78
79 x => { label => 'Time' },
80 y => { label => 'Sine' },
81 );
82
83
84 # --( Managing window interaction )--
85
86 # In scripts and older Term::ReadLine, if you press
87 # the letter 'q' when viewing a plot, you can
88 # re-invoke interaction with:
89 twiddle;
90
91 # query auto-twiddling
92 my $is_auto_twiddline = auto_twiddle;
93 # Turn auto-twiddling on or off
94 auto_twiddle(1);
95 auto_twiddle(0);
96  
97 =head1 DESCRIPTION
98  
99 One of Perl's mottos is to "make easy things easy, and hard things possible."
100 The bulk of the modules provided by the
101 L<PDL::Graphics::Prima|PDL::Graphics::Prima/> distribution
102 focus on the latter half, making hard but very powerful things possible.
103 This module tackles the other half: making easy things easy. This module
104 provides a number of simple functions for quick data plotting so that you can
105 easily get a first look at your data. You can think of this as providing a
106 function-based interface to plotting, in contrast to the GUI/OO interface of
107 the rest of L<PDL::Graphics::Prima|PDL::Graphics::Prima/DESCRIPTION>. Or you
108 can look at this as providing a handy collection of plot (and window)
109 constructors for the standard use cases. Either perspective is basically correct.
110  
111 In addition to making easy plots easy, this module and its documentation are
112 meant to serve as an introduction to L<PDL::Graphics::Prima|PDL::Graphics::Prima/>.
113 If you are new to the libarary, this is where you should start.
114  
115 This module is built on L<the Perl Data Language|PDL> and
116 L<the Prima GUI toolkit|Prima>. You do not need to know much about
117 L<Prima|Prima> to use this tutorial, but you should know
118 L<the basics of PDL|PDL::QuickStart>.
119  
120 When you use this library, you get a handful of functions for quick data
121 plotting that include
122  
123 =over
124  
125 =item lines
126  
127 L<line_plot|/line_plot> takes one or two L<piddle|PDL::Core/pdl>s, one for y and optionally one for
128 x, and makes a L<line plot|PDL::Graphics::Prima::PlotType/ppair::Lines> with
129 them; if you don't give an x L<piddle|PDL::Core/pdl>, it uses
130 L<sequential integers starting from zero|PDL::Basic/xvals>.
131  
132 =item symbols
133  
134 Various symbol plots, like L<cross_plot|/cross_plot> and
135 L<diamond_plot|/diamond_plot>, take one or two L<piddle|PDL::Core/pdl>s, one
136 for y and optionally one for
137 x, and and plots the L<symbol|PDL::Graphics::Prima::PlotType/ppair::Symbols>
138 at the given points; if you don't give an x L<piddle|PDL::Core/pdl>, it uses
139 L<sequential integers starting from zero|PDL::Basic/xvals>.
140  
141 =item functions
142  
143 L<func_plot|/func_plot> takes an I<initial> plot min/max and a L<function reference|perlsub> and
144 makes a L<line plot|PDL::Graphics::Prima::PlotType/ppair::Lines> of the
145 L<function|perlsub>; it can optionally take the number of points to evaluate
146 on each drawing operation; see L<PDL::Graphics::Prima::DataSet/ds::Func>
147  
148 =item histograms
149  
150 L<hist_plot|/hist_plot> takes a L<piddle|PDL::Core/pdl> of data to be plotted and an optional
151 L<bin type|PDL::Graphics::Prima::DataSet/Sets> and plots a
152 L<histogram|PDL::Graphics::Prima::PlotType/ppair::Histogram>. If no bin
153 type is supplied, L<linear binning|PDL::Graphics::Prima::DataSet/bt::Linear>
154 is used.
155  
156 =item images
157  
158 Both L<matrix_plot|/matrix_plot> and L<imag_plot|/imag_plot> take one or
159 three arguments, the first two of which specify the x-bounds and the
160 y-bounds, the third (or only) of which is the matrix to plot
161  
162 =item plot (...)
163  
164 L<plot|/"PLOT FUNCTION"> is a much more powerful routine that takes the same
165 arguments you would pass to
166 the constructor of a L<plot widget|PDL::Graphics::Prima/>, and packs the
167 resulting plot widget in a L<stand-alone window|Prima::Window>.
168  
169 =back
170  
171 And with that, let's look at how to I<use> these to view data!
172  
173 =head1 TUTORIAL
174  
175 To begin, let's assume you have some x/y data that you want to plot with lines
176 connecting them. My canonical example is a sine wave. Here's a complete script
177 to get us started:
178  
179 use PDL;
180 use PDL::Graphics::Prima::Simple;
181 my $x = sequence(100)/10;
182 line_plot($x, $x->sin);
183 print "All done!\n";
184  
185 The C<use PDL> line L<pulls in all the machinery for the Perl Data Language|PDL>
186 and, more importantly, imports the L<C<sequence>|PDL::Basic/sequence> function
187 (among many others) into the current package. On the third line we use that
188 function to generate a bunch of x-data with a spacing of 1/10. In the last
189 line we plot the sine of that sequence of points.
190  
191 When you run the above example script, it will block at the C<line_plot>
192 command and display a L<Prima window|Prima::Window> with your plot. (On the
193 other hand, if you are in the L<pdl shell|perldl>, the plot will be displayed
194 but it will not block your shell if you have a recent version of
195 L<Term::ReadLine>.) We will return to the blocking behavior, and how to call
196 this in a non-blocking fashion, in a little bit.
197  
198 =head2 Interactive Features
199  
200 For now, turn your attention to the plot. This is a highly interactive
201 plot, as are all plots made with
202 L<PDL::Graphics::Prima|PDL::Graphics::Prima/>. In particular,
203 your plot responds to the following user interactions:
204  
205 =over
206  
207 =item right-click zooming
208  
209 Clicking and dragging your right mouse button will zoom into a specific region.
210 You will see a zoom rectangle on the plot until you release the mouse, at which
211 point the plot will be zoomed-in to the region that you selected.
212  
213 =item scroll-wheel zooming
214  
215 You can zoom-in and zoom-out using your scroll wheel. The zooming is designed to
216 keep the data under the mouse at the same location as you zoom in and out.
217 (This is not a 100% guarantee, but for most uses it works about right.)
218  
219 =item dragging/panning
220  
221 Once you have zoomed into a region, you can examine nearby data by clicking and
222 dragging with your left mouse button, much like an interactive map.
223  
224 =item context menu
225  
226 Right-clicking on the plot will bring up a L<context menu|Prima::Menu> with
227 options including restoring auto-scaling, L<copying the current plot image to
228 your clipboard|PDL::Graphics::Prima/copy_to_clipboard>* (to paste directly
229 into, say, Microsoft's PowerPoint or LibreOffice's Impress),
230 and saving the current plot image to a
231 L<postscript|PDL::Graphics::Prima/save_to_postscript> or
232 L<raster|PDL::Graphics::Prima/save_to_file> file. Postscript
233 output is L<always|Prima::PS::Drawable> L<supported|Prima::PS::Printer>, but
234 the supported raster output file formats depend on the L<image libraries and
235 codecs that Prima was able to build against|Prima::image-load>, so are system-
236 and machine-dependent. For additional information on raster images, see
237 L<Prima::Image>.
238  
239 * For reasons not clear to me, copying the plot to the clipboard does not
240 seem to work on Mac and appear to be due to limitations with the X-window
241 bindings.
242  
243 =item resizable
244  
245 When packed into a resizable window (as is the case in this example), the plot
246 can be resized and it will be updated and redrawn smoothly.
247  
248 =back
249  
250 The library lets you
251 L<specify the|PDL::Graphics::Prima::Axis/min, max>
252 L<x- and y-bounds of the plot|PDL::Graphics::Prima::Axis/minmax>, but if you do
253 not specify bounds, the axis bounds will be calculated to tightly fit the data.
254 In fact, the library is designed to automatically choose axis boundaries that fit your
255 data and symbols exactly. (And if you wanted a bit of padding included in that
256 auto-fitting... well... it's on my todo list. :-)
257  
258 =head2 Soapbox
259  
260 Having played around with the plot widget, you probably want to know how to
261 modify it programatically, by adding a L<title|PDL::Graphics::Prima/title> or
262 L<axis labels|PDL::Graphics::Prima::Axis/label>, perhaps. "What sort of
263 options," you ask, "does L<line_plot|/line_plot> accept for me to specify
264 these things?" Well, you can't specify those in your call to
265 L<line_plot|/line_plot>. You either add them to the object after
266 L<line_plot|/line_plot> builds something for you, or you use the more
267 powerful but verbose L<plot function|/"PLOT FUNCTION">.
268  
269 "But WHY?" you ask. "WHY can't I just specify a plot title in
270 L<line_plot|/line_plot> and be done with it?" The reason is simple. The
271 underlying library is built on a very clean and well-thought-out object and
272 I would rather not waste my time creating or your time learning some
273 intermediate API. A means for specifying the plot title in
274 L<line_plot|/line_plot> is the first step down the road of confused mental
275 models. So, it's really in your best interst. Honest. :-)
276  
277 "But WHY?" you ask again. OK, OK, I'll tell you how to essentially get what
278 you want.
279  
280 =head2 Adding axis labels and titles via methods
281  
282 First, you can use the C<line_plot> command to build a
283 L<plot object|PDL::Graphics::Prima/> and return them to you I<without
284 blocking your script.> This will allow you to modify the properties of the
285 L<plot object|PDL::Graphics::Prima/> before it gets displayed. For example, I
286 can L<add a plot title|PDL::Graphics::Prima/title> and
287 L<specifically choose when to view the plot|Prima::Window/execute> like so:
288  
289 use PDL;
290 use PDL::Graphics::Prima::Simple;
291
292 # Non-blocking
293 auto_twiddle(0);
294
295 # Build the plot
296 my $x = sequence(100)/10;
297 my $plot = line_plot($x, $x->sin);
298
299 # Add a title
300 $plot->title('The sine wave');
301
302 # Display the plot
303 twiddle();
304  
305 You next may ask how you modify the
306 L<axis properties|PDL::Graphics::Prima::Axis/>, such as
307 L<setting the bounds|PDL::Graphics::Prima::Axis/min, max>
308 or L<giving them labels|PDL::Graphics::Prima::Axis/label>. The
309 L<axes|PDL::Graphics::Prima::Axis/> are sub-objects of the
310 L<plot|PDL::Graphics::Prima/>, accessed with
311 L<like-named accessors|PDL::Graphics::Prima/x, y>: $plot->x. The
312 properties of the axes that you can modify include the
313 L<min|PDL::Graphics::Prima::Axis/min, max>,
314 L<max|PDL::Graphics::Prima::Axis/min, max>,
315 L<scaling type|PDL::Graphics::Prima::Axis/scaling>, and
316 L<axis label|PDL::Graphics::Prima::Axis/label>, and are discussed
317 in greater detail
318 L<under their own documentation|PDL::Graphics::Prima::Axis/>.
319 Let's see how to set the
320 L<x- and y-axis|PDL::Graphics::Prima/x, y>
321 L<labels|PDL::Graphics::Prima::Axis/label>:
322  
323 use PDL;
324 use PDL::Graphics::Prima::Simple;
325
326 # Build the plot
327 auto_twiddle(0);
328 my $x = sequence(100)/10;
329 my $plot = line_plot($x, $x->sin);
330
331 # Add a title and axis labels
332 $plot->title('The Harmonic Oscillator');
333 $plot->x->label('time (s)');
334 $plot->y->label('displacement (cm)');
335
336 # Display the plot
337 twiddle();
338  
339 =head2 Working with plot objects in the PDL shell
340  
341 NOTE: The current state of readline integration, and its work-around, are
342 in a state of flux. These docs are not entirely accurate. But they're
343 close enough. Expect this to get fixed soon.
344  
345 NOTE: L<Term::ReadLine::Perl> is a pure-perl implementation of L<Term::ReadLine::Gnu>
346 and it is very nice. However, it does not play nicely with the Prima readline
347 integration for reasons I do not yet fully understand. In particular, the
348 displayed text and cursor position are always displayed one step "behind" what
349 you last indicated with the navigation keys (but they are always up-to-date when
350 you type normal letters). If you have any ideas for how to remedy this, please
351 let me know! Thanks!
352  
353 You can do the same sorts of manipulations from the
354 console and see the updates as soon as you press enter. The equivalent
355 commands as the ones shown above are:
356  
357 pdl> use PDL::Graphics::Prima::Simple
358 pdl> auto_twiddle(0)
359 pdl> $x = sequence(100)/10
360 # After the next commant, the line plot window will pop up
361 pdl> $plot = line_plot($x, $x->sin)
362 pdl> $plot->title('The Harmonic Oscillator')
363 pdl> $plot->x->label('time (s)')
364 pdl> $plot->y->label('displacement (cm)')
365  
366 Each method call to the plot command will cause the plot to get updated with the
367 new element or feature.
368  
369 =head2 Axis minima and maxima
370  
371 If you want to set the axis bounds, you can use the
372 L<min|PDL::Graphics::Prima::Axis/min, max>,
373 L<max|PDL::Graphics::Prima::Axis/min, max> and
374 L<minmax|PDL::Graphics::Prima::Axis/minmax> functions. For example,
375 continuing from the PDL shell, this sets the x-minimum to zero:
376  
377 pdl> $plot->x->min(0)
378  
379 If you drag the plot around with your mouse and want to see the current
380 value of the min, you could say:
381  
382 pdl> p $plot->x->min
383  
384 This will print two numbers, actually, the second being a boolean flag indicating
385 whether or not autoscaling is on. To just get the minimum value, call the C<min>
386 method in scalar context:
387  
388 pdl> p scalar($plot->x->min)
389  
390 If you want to re-enable autoscaling, you pass in a special value for the
391 min or max (or both) denoted by the constant
392 L<C<lm::Auto>|PDL::Graphics::Prima::Limits/lm::Auto> as in
393  
394 # Set the x-axis to autoscaling
395 pdl> $plot->x->minmax(lm::Auto, lm::Auto);
396 # Set the y-minimum to autoscaling
397 pdl> $plot->y->min(lm::Auto);
398  
399 =head2 Histograms and images
400  
401 I've only spoken so far about connecting x/y data with lines, but there are
402 other ways to visualize x/y data, and even other forms of data you may wish
403 to represent. For example, if you want to visualize a distribution of data,
404 you would want to use a histogram:
405  
406 use PDL;
407 use PDL::Graphics::Prima::Simple;
408
409 # Generate 100 samples with mean 0 and standard deviation 1
410 my $distribution = grandom(100);
411 hist_plot($distribution);
412  
413 Or, you may have an image of data that you want to view.
414  
415 use PDL;
416 use PDL::Graphics::Prima::Simple;
417
418 # Generate 100 samples with mean 0 and standard deviation 1
419 my $image = rvals(100, 100)
420 matrix_plot($image);
421  
422 And you won't be surprised to learn there are many other ways to display x/y
423 data, as well. But let's keep moving.
424  
425 =head2 Adding DataSets
426  
427 What if you wanted to plot additional data along with the current data? You
428 do this by creating a new L<DataSet|PDL::Graphics::Prima::DataSet/>. Let's start
429 by adding a L<DataSet|PDL::Graphics::Prima::DataSet/> with the cosine of a
430 slightly different x-range:
431  
432 use PDL;
433 use PDL::Graphics::Prima::Simple;
434
435 # Build the plot
436 my $x = sequence(100)/10;
437 my ($window, $plot) = line_plot($x, $x->sin);
438
439 # Add a new dataset
440 my $x2 = sequence(100)/10 + 1;
441 $plot->dataSets{'cosine'} = ds::Pair($x2, $x2->cos);
442
443 # Display the plot
444 $window->execute;
445  
446 The important line in this example is the part that includes
447 L<C<ds::Pair>|PDL::Graphics::Prima::DataSet/ds::Pair>. Like
448 L<C<lm::Auto>|PDL::Graphics::Prima::Limits/lm::Auto>,
449 L<C<ds::Pair>|PDL::Graphics::Prima::DataSet/ds::Pair> is a function that
450 uses a short prefix so that it's fast and easy to type. This is a L<common
451 idiom in the Prima toolkit|Prima::Const/> (though in the toolkit it is used
452 exclusively for specifying useful constants).
453 L<C<ds::Pair>|PDL::Graphics::Prima::DataSet/ds::Pair> is just a short-hand
454 for a constructor with an enormous name:
455  
456 # Short form
457 my $ds = ds::Pair($x, $y);
458 # Long form
459 my $ds = PDL::Graphics::Prima::DataSet::Pair->new(x => $x, y => $y);
460  
461 If you actually run that example, you will notice that the sine cureve is
462 plotted as a line, just as before, but the cosine curve is plotted with a
463 collection of unconnected diamonds. If you want to plot the cosine curve
464 with a line, you need to specify the line plot type:
465  
466 ...
467 # Add a new dataset
468 $plot->dataSets{'cosine'} = ds::Pair($x, $x->cos,
469 plotType => ppair::Lines
470 );
471 ...
472  
473 Perl is supposed to Do What I Mean, and you could argue that this is a case
474 of the plotting library I<not> doing what you mean: the cosine curve "should"
475 be plotted with L<lines|PDL::Graphics::Prima::PlotType/ppair::Lines>, because
476 that's how the sine curve was plotted. However, I believe that such behavior
477 violates the Principle of Least Surprise. The default plot type for pairwise
478 data is L<diamonds|PDL::Graphics::Prima::PlotType/ppair::Diamonds>, so if you
479 didn't specify a plot type, you actually meant to plot diamonds.
480  
481 That brings us to the important distinction between a
482 L<DataSet|PDL::Graphics::Prima::DataSet/> and a
483 L<PlotType|PDL::Graphics::Prima::PlotType/>. A
484 L<DataSet|PDL::Graphics::Prima::DataSet/> contains the x/y data, or the
485 distribution, or the image matrix that you want shown, along with one or
486 more means of visualizing that data. The means for visualizing that data are
487 what are called L<PlotType|PDL::Graphics::Prima::PlotType/>s, and different
488 L<DataSet|PDL::Graphics::Prima::DataSet/>s use distinct
489 L<PlotType|PDL::Graphics::Prima::PlotType/>s.
490  
491 =head2 Adding axis labels and titles at construction
492  
493 Although interacting with the plot object after creation is fun, it is also
494 nice to be able to specify all of these settings when the plot is initially
495 created. I have already explained how limited the super-simple interface is,
496 and L<why I chose to restrict it to be so limited|/Soapbox>. In light of that,
497 I now show you how to specify all of these properties and more with a single
498 C<plot> command.
499  
500 Let's begin by examining the L<line_plot|/line_plot> command. The documentation
501 below states that the function call with args C<($x, $y)> is equivalent to
502 this line:
503  
504 plot(-data => ds::Pair($x, $y, plotType => ppair::Lines));
505  
506 Let's expand that into a full example and include the title, x-label, and
507 y-label:
508  
509 use PDL;
510 use PDL::Graphics::Prima::Simple;
511
512 # Build the plot
513 my $x = sequence(100)/10;
514 plot(
515 # Create the DataSet with the Lines pairwise plotType
516 -data => ds::Pair($x, $x->sin,
517 plotType => ppair::Lines
518 ),
519
520 # Set the title and axis labels
521 title => 'The Harmonic Oscillator',
522 x => { label => 'time (s)' },
523 y => { label => 'displacement (cm)' },
524 );
525  
526 Notice that all arguments to L<plot|/"PLOT FUNCTION"> are key/value pairs.
527 There is a clean, heierarchical structure to the function call, and it is
528 clear simply by examining the punctuation which settings go with which piece.
529 For example, the L<ppair::Lines|PDL::Graphics::Prima::PlotType/ppair::Lines>
530 argument clearly belongs to the L<ds::Pair>. In this case, we use data
531 structures that Perl provides to help convey the structure of the plot we
532 are trying to create.
533  
534 =head2 Blocking behavior
535  
536 Precisely what happens when you call these functions depends on your
537 environment. These functions always create a stand-alone window with the plot,
538 but they may or may not pause your script or shell while you interact with
539 the plot. In regular Perl scripts, the code will block at these function
540 calls until you close the window or press 'q' in one of the plot windows. For
541 some folks, when using the PDL shell the functions return immediately,
542 letting them peform more calculations or create new plots while keeping other
543 plot windows open. For other folks, it's possible to go back and forth
544 between an active plot and an inactive PDL shell, or an active shell and an
545 inactive plot. From the shell, the C<twiddle> function makes the plot active;
546 from the plot, pressing 'q' returns focus to the shell.
547  
548 The main drawback of using the Simple interface instead of the full-blown
549 widget interface is that it differs from the normal Prima GUI application
550 interface. I hope that this makes it easier for you to get started with this
551 plotting library, but I hope that you also take the time to learn how to
552 write Prima applications, with the Plot widget as just one component for
553 user interaction. If you need any substantial amount of user interaction or
554 real-time behavior, I suggest you work with the full Prima toolkit.
555  
556 You may find yourself working on a script and wanting to create multiple plot
557 windows at once, without blocking until all of them are ready. You do this by
558 explicitly turning off autotwiddling. Specifically, you would write something
559 like this:
560  
561 my $was_auto_twiddling = auto_twiddle;
562 auto_twiddle(0);
563
564 # ... plotting operations ...
565
566 # All done; restore previous autotwiddling
567 # state and let the use interact:
568 auto_twiddle($was_auto_twiddling);
569 twiddle();
570  
571 Although you can plot multiple L<DataSet|PDL::Graphics::Prima::DataSet/>s in the
572 same plot window, and you can simultaneously build multiple plot windows, a
573 limitation of this Simple interface is that you cannot create multiple
574 independent plots in the same window. This is achieved using the full GUI
575 toolkit by creating two plot widgets packed into a larger container widget. A
576 tutorial for this sort of thing is in the works but hasn't made it into the
577 distribution yet. Stay tuned!
578  
579 Having covered that introductory material, let's cover things a little more
580 systematically.
581  
582 =head1 SIMPLEST FUNCTIONS
583  
584 These functions are bare-bones means for visualizing your data that are no
585 more than simple wrappers around the more powerful L<plot|/"PLOT FUNCTION">
586 function. If you just want to have a quick look at your data, you should start
587 with these. These functions can return the plot widget itself, allowing you
588 to modify it, but see the L<plot|/"PLOT FUNCTION"> if want more control
589 over your plot, such as plotting multiple data sets, using variable or
590 advanced symbols, using multiple plot types, controlling the axis scaling,
591 using colors, or setting the title or axis labels.
592  
593 In all of these plots, bad values in x and y are simply omitted.
594  
595 =over
596  
597 =item line_plot ([$x], $y)
598  
599 The C<line_plot> function takes either one or two arguments. In the one-argument
600 form, the argument is a piddle with your y data. In the two argument form the
601 arguments are a piddle with your x data and a piddle with your y data. The
602 function plots them by drawing black lines on a white background from one point
603 to the next. Usually C<$x> and C<$y> will have the same dimensions, but you can
604 use any data that are PDL-thread compatible. For example, here's a way to
605 compare three sets of data that have the exact same x-values:
606  
607 my $x = sequence(100)/10;
608 my $y = sequence(3)->transpose + sin($x);
609
610 # Add mild linear trends to the first and second:
611 use PDL::NiceSlice;
612 $y(:, 0) += $x/5;
613 $y(:, 1) -= $x/6;
614
615 line_plot($x, $y);
616  
617 The x-values do not need to be sorted. For example, this plots a sine wave sine
618 wave oscillating horizontally:
619  
620 my $y = sequence(100)/10;
621 my $x = sin($y);
622 line_plot($x, $y);
623  
624 For the truly lazy, you can simply supply the y-values:
625  
626 my $y = sin(sequence(100)/10);
627 line_plot($y);
628  
629 Bad values in your data, if they exist, will simply be skipped, inserting a
630 gap into the line.
631  
632 For the two-argument form, to generate the same plot using the
633 L<plot|/"PLOT FUNCTION"> command, you would type this:
634  
635 plot(-data => ds::Pair($x, $y, plotType => ppair::Lines));
636  
637 For the one-argument form, you would type this:
638  
639 plot(-data => ds::Pair($y->xvals, $y, plotType => ppair::Lines));
640  
641 =cut
642  
643 sub _get_pairwise_data {
644 # If one arg, and it's a piddle, return a sequence and that piddle as x/y
645 if (@_ == 1 and eval { $_[0]->isa('PDL') } ) {
646 return (PDL->sequence($_[0]->dim(0)), $_[0]);
647 }
648 # If two args, and both are piddles, return them as x/y
649 elsif (@_ == 2 and eval{$_[0]->isa('PDL') and $_[1]->isa('PDL')} ) {
650 return @_;
651 }
652
653 # Neither of the above conditions applied: determine the function name, croak
654 my $function_name = (caller(1))[3];
655 $function_name =~ s/.*:://;
656 croak("$function_name expects either one piddle (y-data) or two piddles (x- and y-data)");
657 }
658  
659 sub line_plot {
660 @_ = (-data => ds::Pair(_get_pairwise_data(@_), plotType => ppair::Lines));
661 goto &plot;
662 }
663  
664 =item circle_plot ([$x], $y)
665  
666 Plots filled circles at (x, y). (See L<line_plot|/line_plot> for a more detailed description.)
667 Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument forms include:
668  
669 plot(-data => ds::Pair($x, $y, plotType => ppair::Blobs));
670 plot(-data => ds::Pair(
671 $x,
672 $y,
673 plotType => ppair::Symbol(
674 filled => 'yes',
675 N_points => 0,
676 ),
677 ));
678  
679 =cut
680  
681 sub circle_plot {
682 @_ = (-data => ds::Pair(_get_pairwise_data(@_), plotType => ppair::Blobs));
683 goto &plot;
684 }
685  
686 =item triangle_plot ([$x], $y)
687  
688 Plots filled upright triangles at (x, y). (See L<line_plot|/line_plot> for a more detailed
689 description.) Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument
690 form include:
691  
692 plot(-data => ds::Pair(
693 $x,
694 $y,
695 plotType => ppair::Triangles(filled => 1)
696 ));
697 plot(-data => ds::Pair(
698 $x,
699 $y,
700 plotType => ppair::Symbol(
701 filled => 'yes',
702 N_points => 3,
703 orientation => 'up',
704 ),
705 ));
706  
707 =cut
708  
709 sub triangle_plot {
710 @_ = (-data => ds::Pair(_get_pairwise_data(@_)
711 , plotType => ppair::Triangles(filled => 1)));
712 goto &plot;
713 }
714  
715 =item square_plot ([$x], $y)
716  
717 Plots filled squares at (x, y). (See L<line_plot|/line_plot> for a more detailed description.)
718 Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument form include:
719  
720 plot(-data => ds::Pair(
721 $x,
722 $y,
723 plotType => ppair::Squares(filled => 1)
724 ));
725 plot(-data => ds::Pair(
726 $x,
727 $y,
728 plotType => ppair::Symbol(
729 filled => 'yes',
730 N_points => 4,
731 orientation => 45,
732 ),
733 ));
734  
735 =cut
736  
737 sub square_plot {
738 @_ = (-data => ds::Pair(_get_pairwise_data(@_)
739 , plotType => ppair::Squares(filled => 1)));
740 goto &plot;
741 }
742  
743 =item diamond_plot ([$x], $y)
744  
745 Plots filled diamonds at (x, y). (See L<line_plot|/line_plot> for a more detailed description.)
746 Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument form include:
747  
748 plot(-data => ds::Pair($x, $y));
749 plot(-data => ds::Pair(
750 $x,
751 $y,
752 plotType => ppair::Diamonds(filled => 1)
753 ));
754 plot(-data => ds::Pair(
755 $x,
756 $y,
757 plotType => ppair::Symbol(
758 filled => 'yes',
759 N_points => 4,
760 ),
761 ));
762  
763 =cut
764  
765 sub diamond_plot {
766 @_ = (-data => ds::Pair(_get_pairwise_data(@_)));
767 goto &plot;
768 }
769  
770 =item cross_plot ([$x], $y)
771  
772 Plots crosses (i.e. plus symbols) at (x, y). (See L<line_plot|/line_plot> for a more detailed
773 description.) Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument
774 form include:
775  
776 plot(-data => ds::Pair($x, $y, plotType => ppair::Crosses));
777 plot(-data => ds::Pair(
778 $x,
779 $y,
780 plotType => ppair::Symbol(
781 N_points => 4,
782 skip => 0,
783 ),
784 ));
785  
786 =cut
787  
788 sub cross_plot {
789 @_ = (-data => ds::Pair(_get_pairwise_data(@_), plotType => ppair::Crosses));
790 goto &plot;
791 }
792  
793 =item X_plot ([$x], $y)
794  
795 Plots X symbols at (x, y). (See L<line_plot|/line_plot> for a more detailed description.)
796 Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument form include:
797  
798 plot(-data => ds::Pair($x, $y, plotType => ppair::Xs));
799 plot(-data => ds::Pair(
800 $x,
801 $y,
802 plotType => ppair::Symbol(
803 N_points => 4,
804 skip => 0,
805 orientation => 45,
806 ),
807 ));
808  
809 =cut
810  
811 sub X_plot {
812 @_ = (-data => ds::Pair(_get_pairwise_data(@_), plotType => ppair::Xs));
813 goto &plot;
814 }
815  
816 =item asterisk_plot ([$x], $y)
817  
818 Plots five-pointed asterisks at (x, y). (See L<line_plot|/line_plot> for a more detailed
819 description.) Equivalent L<plot|/"PLOT FUNCTION"> commands for the two-argument
820 form include:
821  
822 plot(-data => ds::Pair(
823 $x,
824 $y,
825 plotType => ppair::Asterisks(N_points => 5)
826 ));
827 plot(-data => ds::Pair(
828 $x,
829 $y,
830 plotType => ppair::Symbol(
831 N_points => 5,
832 skip => 0,
833 orientation => 'up',
834 ),
835 ));
836  
837 =cut
838  
839 sub asterisk_plot {
840 @_ = (-data => ds::Pair(_get_pairwise_data(@_)
841 , plotType => ppair::Asterisks(N_points => 5)));
842 goto &plot;
843 }
844  
845  
846 =item func_plot ($x_min, $x_max, $func_ref, [$N_points])
847  
848 The C<func_plot> function takes three or four arguments and plots a function.
849 The first two arguments are the initial x-bounds (min and max); the third
850 argument is the function that you want to plot; the optional fourth argument is
851 the number of points that you want to use in generating the plot. The resulting
852 figure will have a black line drawn against a white background.
853  
854 The function itself will be called whenever the plot needs to be redrawn. It
855 will be passed a single argument: a piddle with sequential x-points at which
856 the function should be evaluated. The function should return a piddle of
857 y-points to be plotted. Here are some examples:
858  
859 # Plot PDL's exponential function:
860 func_plot (1, 5, \&PDL::exp);
861 # this time with higher resolution:
862 func_plot (1, 5, \&PDL::exp, 1000);
863
864 # Plot a rescaled tangent function:
865 func_plot (1, 5, sub {
866 my $xs = shift;
867 return 5 * ($xs / 4)->tan
868 });
869 # or equivalently, if you "use PDL":
870 func_plot (1, 5, sub {
871 my $xs = shift;
872 return 5 * tan($xs / 4);
873 });
874  
875 Your function can return bad values, in which case they will not be drawn. For
876 example, here is a function that plots a decaying exponential, but only for
877 values of x greater than or equal to zero. It starts with an initial view of
878 x running from 0 to 4:
879  
880 func_plot (0, 4, sub {
881 my $xs = shift;
882 my $ys = exp(-$xs);
883 return $ys->setbadif($xs < 0);
884 });
885  
886 The return value must have thread-compatible dimensions, but that means that they
887 do not need to be identical to the input x. For example, a scalar is
888 thread-compatible with a vector, so the following will create a line at a
889 y-value of 1:
890  
891 func_plot (0, 4, sub { 1 });
892  
893 Or, you can return a piddle with more dimensions than the input:
894  
895 func_plot (0, 4, sub {
896 my $xs = shift;
897 my $first_ys = sin($xs);
898 my $second_ys = cos($xs) + 3;
899 return $first_ys->cat($second_ys);
900 });
901  
902  
903 If you do not specify the number of points to draw, the equivalent L<plot|/"PLOT FUNCTION">
904 command is this:
905  
906 plot(
907 -data => ds::Func($func_ref),
908 x => { min => $xmin, max => $xmax },
909 );
910  
911 If you do specify the number of points to draw, the equivalent L<plot|/"PLOT FUNCTION"> command
912 is this:
913  
914 plot(
915 -data => ds::Func($func_ref, N_points => $N_points),
916 x => { min => $xmin, max => $xmax },
917 );
918  
919 =cut
920  
921 sub func_plot {
922 croak("func_plot expects three or four arguments: the x min and max, the function reference,\n"
923 . " and, optionally, the number of points to plot")
924 unless @_ == 3 or @_ == 4;
925 my ($xmin, $xmax, $func_ref, $N_points) = @_;
926 @_ = (
927 -data => ds::Func($func_ref, ($N_points ? (N_points => $N_points) : ())),
928 x => {
929 min => $xmin,
930 max => $xmax,
931 },
932 );
933 goto &plot;
934 }
935  
936 =item hist_plot ($distribution, [$bin_type])
937  
938 The C<hist_plot> function takes a distribution of data that you want to
939 visualize and an optional binning type. This is a fairly simple wrapper
940 around the L<linear binning type|PDL::Graphics::Prima::DataSet/bt::Linear>
941 for the L<Distribution DataSet|PDL::Graphics::Prima::DataSet/Distribution>
942 using the
943 L<histogram pairwise plot type|PDL::Graphics::Prima::PlotType/Histogram>.
944 It plots the histogram as black-outlined rectangles against a white
945 background.
946  
947 The equivalent L<plot|/"PLOT FUNCTION"> commands is:
948  
949 plot(-data => ds::Dist($distribution));
950  
951 A lot of defaults go into that, so it might be useful to see some of those
952 expanded a bit:
953  
954 plot(-data =>
955 ds::Dist($distribution,
956 plotType => ppair::Histogram,
957 binning => bt::Linear
958 )
959 );
960  
961 You could tweak the binning, for example by using a
962 L<strict logarithmic binning|PDL::Graphics::Prima::DataSet/bt::StrictLog>,
963 which throws an exception if your distribution includes negative data:
964  
965 hist_plot($distribution, bt::StrictLog);
966  
967 or you could specify that you want 15 bins:
968  
969 hist_plot($distribution, bt::Linear(nbins => 15));
970  
971 There is quite a bit more to explore here, and it will be covered below.
972  
973 =cut
974  
975 sub hist_plot {
976 my ($piddle, $subref) = @_;
977 croak("hist_plot expects a piddle as the first argument")
978 unless eval{$piddle->isa('PDL')};
979 my @bin_args;
980 if (defined $subref) {
981 croak("hist_plot expects a optional bin type or subref")
982 if ref($subref) ne ref(sub{});
983 @bin_args = (binning => $subref);
984 }
985 @_ = (-data => ds::Dist($piddle, @bin_args));
986 goto &plot;
987 }
988  
989 =item matrix_plot ([$x_edges, $y_edges,] $matrix)
990  
991 The C<matrix_plot> function plots a grayscale rendering of a matrix with
992 the largest values closest to black, the smallest values closest to white.
993 (For the opposite color sense, see L<imag_plot|/imag_plot>.) This function
994 takes either one or three arguments. The first designates the x min and max
995 of the plot; the second designates the y min and max of the plot, and the
996 third (or only) specifies a matrix that you want to have
997 plotted in grayscale. The x-edges and y-edges arguments should be
998 two-element array references, such as:
999  
1000 matrix_plot ([0 => 5], [1 => 10], $matrix);
1001  
1002 Bad values, if your matrix has any, are skipped. This means that you will have
1003 a white spot in its place (since the background is white), which is not
1004 great. Future versions may use a different color to specify bad values.
1005  
1006 Not specifying edges looks like this:
1007  
1008 matrix_plot ($matrix);
1009  
1010 and its equivalent L<plot|/"PLOT FUNCTION"> commands are:
1011  
1012 plot(-image => ds::Grid(
1013 $matrix,
1014 x_bounds => [0, 1],
1015 y_bounds => [0, 1],
1016 ));
1017 plot(-image => ds::Grid(
1018 $matrix,
1019 x_bounds => [0, 1],
1020 y_bounds => [0, 1],
1021 plotType => pgrid::Matrix,
1022 ));
1023  
1024 Specifying edges looks like this:
1025  
1026 matrix_plot ([0 => 5], [1 => 10], $matrix);
1027  
1028 and the quivalent is:
1029  
1030 plot(-image => ds::Grid(
1031 $matrix,
1032 x_bounds => [0, 5],
1033 y_bounds => [1, 10],
1034 plotType => pgrid::Matrix,
1035 ));
1036  
1037 =cut
1038  
1039 sub matrix_plot {
1040 my ($x, $y, $matrix);
1041 if (@_ == 1) {
1042 $matrix = $_[0];
1043 my @dims = $matrix->dims;
1044 $x = [0, $dims[0]];
1045 $y = [0, $dims[1]];
1046 ($matrix) = @_;
1047 }
1048 elsif (@_ == 3) {
1049 ($x, $y, $matrix) = @_;
1050 }
1051 else {
1052 croak("matrix_plot expects an image, optionally preceeded by its x- and y-limits:\n"
1053 . "matrix_plot ([x0, xf], [y0, yf], \$image)")
1054 }
1055
1056 @_ = (-image => ds::Grid(
1057 $matrix,
1058 x_bounds => $x,
1059 y_bounds => $y,
1060 ));
1061 goto &plot;
1062 }
1063  
1064 =item imag_plot ([$x_edges, $y_edges,] $matrix)
1065  
1066 The C<imag_plot> function is identical to L<matrix_plot|/matrix_plot> except that the
1067 color scaling runs from black (lowest) to white (highest). This form is
1068 especially useful for plotting black and white images, in which case the
1069 brightest points should be white.
1070  
1071 Omitting edges, the command looks like this:
1072  
1073 imag_plot($matrix);
1074  
1075 which has the equivalent L<plot|/"PLOT FUNCTION"> command:
1076  
1077 plot(-image => ds::Grid(
1078 $matrix,
1079 x_bounds => [0, 1],
1080 y_bounds => [0, 1],
1081 plotType => pgrid::Matrix(
1082 palette => pal::BlackToWhite
1083 ),
1084 ));
1085  
1086 Specifying edges looks like this:
1087  
1088 imag_plot ([0 => 5], [1 => 10], $matrix);
1089  
1090 and the quivalent is:
1091  
1092 plot(-image => ds::Grid(
1093 $matrix,
1094 x_bounds => [0, 5],
1095 y_bounds => [1, 10],
1096 plotType => pgrid::Matrix(
1097 palette => pal::BlackToWhite
1098 ),
1099 ));
1100  
1101 =cut
1102  
1103 sub imag_plot {
1104 my ($x, $y, $matrix);
1105 if (@_ == 1) {
1106 $matrix = $_[0];
1107 my @dims = $matrix->dims;
1108 $x = [0, $dims[0]];
1109 $y = [0, $dims[1]];
1110 ($matrix) = @_;
1111 }
1112 elsif (@_ == 3) {
1113 ($x, $y, $matrix) = @_;
1114 }
1115 else {
1116 croak("imag_plot expects an image, optionally preceeded by its x- and y-limits:\n"
1117 . "imag_plot ([x0, xf], [y0, yf], \$image)")
1118 }
1119
1120 @_ = (-image => ds::Grid(
1121 $matrix,
1122 x_bounds => $x,
1123 y_bounds => $y,
1124 plotType => pgrid::Matrix(
1125 palette => pal::BlackToWhite
1126 ),
1127 ));
1128 goto &plot;
1129 }
1130  
1131 =back
1132  
1133 =head1 PLOT FUNCTION
1134  
1135 The C<plot> function is the real workhorse of this module. Not only does it
1136 provide the functionality behind all of the above simple functions, but it
1137 also lets you plot multiple L<DataSet|PDL::Graphics::Prima::DataSet/>s, specify
1138 axis labels and a plot title, direct the axis scaling (linear or logarithmic), and set many other properties
1139 of the plot.
1140  
1141 Arguments that you pass to this function are almost identical to the arguments
1142 that you would use to create a Plot widget, so it serves as an excellent sandbox
1143 for playing with the widget's constructor. Also, once you understand how to use
1144 this function, using the actual widget in an interactive GUI script is simply a
1145 matter of understanding how to structure a GUI program.
1146  
1147 The C<plot> function takes options and L<DataSet|PDL::Graphics::Prima::DataSet/>
1148 specifications as key/value pairs. The basic usage of C<plot> looks like this:
1149  
1150 plot(
1151 -dataset1 => ds::Pair($x1, $y1, ...options...),
1152 x => {
1153 axis => options,
1154 },
1155 -dataset2 => ds::Pair($x2, $y2, ...options...),
1156 y => {
1157 axis => options,
1158 },
1159 -mydist => ds::Set($data, ...options...),
1160 title => 'Title!',
1161 titleSpace => 60,
1162 -the_image => ds::Grid($image, ...options...),
1163 ... Prima Drawable options ...
1164 );
1165  
1166 Notice that some of the keys begin with a dash while others do not. Any key
1167 that begins with a dash should be followed by a
1168 L<DataSet|PDL::Graphics::Prima::DataSet/> object (created using the C<ds::xxx>
1169 constructors). You can use any name that you wish for your
1170 L<DataSet|PDL::Graphics::Prima::DataSet/>s, the only requirement is that the name
1171 begins with a dash. (The dash is optional when it comes time to retrieve the
1172 L<DataSet|PDL::Graphics::Prima::DataSet/> later.) The keys that do not begin with
1173 a dash are Plot options. The Plot widget has a
1174 handful of Plot-specific properties, but you can also specify any property of a
1175 L<Prima::Widget> object.
1176  
1177 In the world of C<PDL::Graphics::Prima>, the fundamental object is the Plot.
1178 Each plot can hold one or more L<DataSet|PDL::Graphics::Prima::DataSet/>s, and
1179 each L<DataSet|PDL::Graphics::Prima::DataSet/> is visualized using one or more
1180 L<PDL::Graphics::Prima::PlotType/>s. This makes the plotType the simplest element
1181 to discuss, so I'll start there.
1182  
1183 =head2 Plot Types
1184  
1185 Each L<DataSet|PDL::Graphics::Prima::DataSet/> can have one or more plotTypes. If
1186 you only want to specify a
1187 single plotType, you can do so by specifying it after the plotType key for your
1188 L<DataSet|PDL::Graphics::Prima::DataSet/>:
1189  
1190 -data => ds::Pair(
1191 ...
1192 plotType => ppair::Squares,
1193 ...
1194 )
1195  
1196 You can specify multiple plotTypes by passing them in an anonymous array:
1197  
1198 -data => ds::Pair(
1199 ...
1200 plotTypes => [ppair::Triangles, ppair::Lines],
1201 ...
1202 )
1203  
1204 (Note that the singular and plural keys C<plotType> and C<plotTypes> are
1205 interchangeable. Use whichever is appropriate.)
1206  
1207 All the plotTypes take key/value paired arguments. You can specify various
1208 L<Prima::Drawable|Prima::Drawable/> properties like
1209 L<lineWidth|Prima::Drawable/lineWidth> or L<color|Prima::Drawable/color>; you
1210 can pass plotType-specific options like symbol size
1211 (for L<ppair::Symbol|PDL::Graphics::Prima::PlotType/ppair::Symbol> and its
1212 derivatives) using the C<size> key or the baseline height for
1213 L<ppair::Histogram|PDL::Graphics::Prima::PlotType/ppair::Histogram> using the
1214 C<baseline> key; and some of the plotTypes have required arguments, such as
1215 at least one error bar specification with
1216 L<ppair::ErrorBars|PDL::Graphics::Prima::PlotType/ppair::ErrorBars>. To create
1217 L<red|Prima::Const/cl> L<blobs|PDL::Graphics::Prima::PlotType/ppair::Blobs>,
1218 you would use something like this:
1219  
1220 ppair::Blobs(color => cl::LightRed)
1221  
1222 To create L<blobs|PDL::Graphics::Prima::PlotType/ppair::Blobs> of all
1223 different colors, you would use the plural C<colors>
1224 key and specify a piddle with Color values. (That's discussed below in an
1225 example.) To specify a 5-pixel line width for a Lines plotType, you would say
1226  
1227 ppair::Lines(lineWidth => 5)
1228  
1229 When a L<DataSet|PDL::Graphics::Prima::DataSet/> gets drawn, it draws the
1230 different plotTypes in the order
1231 specified. For example, suppose you specify C<cl::Black> filled triangles and
1232 C<cl::LightRed> lines. If the triangles are specified first, they will have red
1233 lines drawn through them, and if the triangles are second, the triangles will
1234 be drawn over the red lines.
1235  
1236 Each L<DataSet|PDL::Graphics::Prima::DataSet/> has a default plot type. For
1237 L<Dist|PDL::Graphics::Prima::DataSet/Dist>s, it is
1238 L<ppair::histogram|PDL::Graphics::Prima::PlotType/ppair::Histogram>. For
1239 L<Pairs|PDL::Graphics::Prima::DataSet/Pair>, it is
1240 L<ppair::Diamonds|PDL::Graphics::Prima::PlotType/ppair::Diamonds>. For
1241 L<Grids|PDL::Graphics::Prima::DataSet/>, it is
1242 L<pgrid::Matrix|PDL::Graphics::Prima::PlotType/pgrid::Matrix>. If you
1243 want to use a different plotType, you need to specify it as illustrated
1244 by the translations given in the super-simple examples above. The plotTypes are
1245 discussed thoroughly in
1246 L<PDL::Graphics::Prima::PlotType|PDL::Graphics::Prima::PlotType/>, and are
1247 summarized below:
1248  
1249 Pair plotTypes
1250 ==============
1251 ppair::Lines - lines from point to point
1252 ppair::TrendLines - a linear fit to the data
1253 ppair::Blobs - blobs (filled ellipses) with specifiable x- and y- radii
1254 ppair::Symbols - open or filled regular geometric shapes with many options:
1255 size, orientation, number of points, skip pattern, and fill
1256 ppair::Triangles - open or filled triangles with specifiable
1257 orientations and sizes
1258 ppair::Squares - open or filled squares with specifiable sizes
1259 ppair::Diamonds - open or filled diamonds with specifiable sizes
1260 ppair::Stars - open or filled star shapes with specifiable sizes,
1261 orientations, and number of points
1262 ppair::Asterisks - asterisk shapes with specifiable size, orientation, and
1263 number of points
1264 ppair::Xs - four-point asterisks that look like xs, with specifiable
1265 sizes
1266 ppair::Crosses - four-point asterisks that look like + signs, with
1267 specifiable sizes
1268 ppair::Spikes - spikes to (x,y) from a specified vertical or horizontal
1269 baseline
1270 ppair::Histogram - histograms with specifiable baseline and top padding
1271 ppair::ErrorBars - error bars with specified x/y errors and cap sizes
1272
1273
1274 Grid plotTypes
1275 ==============
1276 pgrid::Matrix - colored rectangles, i.e. images
1277  
1278 More plot types are planned, but the ones listed above are the currently
1279 implemented ones.
1280  
1281 The plotTypes are the simplest unit in L<PDL::Graphics::Prima/>. The next
1282 largest unit is the L<DataSet|PDL::Graphics::Prima::DataSet/>, which not only
1283 holds data of various kinds, but
1284 also holds the plotTypes that are to be applied to the given data.
1285  
1286 =head2 DataSets
1287  
1288 You can plot one or more sets of data on a given Plot. You do this by specifying
1289 the L<DataSet|PDL::Graphics::Prima::DataSet/>'s name with a dash, followed by a
1290 L<DataSet|PDL::Graphics::Prima::DataSet/> constructor. The
1291 L<DataSet|PDL::Graphics::Prima::DataSet/> constructor specifies the properties of
1292 your L<DataSet|PDL::Graphics::Prima::DataSet/>, including the data
1293 itself along with the plotType or plotTypes.
1294  
1295 In addition to the two types that I have already alluded to, namely
1296 L<Pairs|PDL::Graphics::Prima::DataSet/Pair> and
1297 L<Grids|PDL::Graphics::Prima::DataSet/Grid>, there are a collection of
1298 derived L<Datasets|PDL::Graphics::Prima::DataSet/>. These include the
1299 L<Function-based DataSet|PDL::Graphics::Prima::DataSet/Func> and the
1300 L<Distribution Dataset|PDL::Graphics::Prima::DataSet/Dist>.
1301  
1302 L<The Pairs DataSet|PDL::Graphics::Prima::DataSet/Pair> targets x/y paired data
1303 and lets you visualize trends and correlations between two collections of data.
1304 The L<constructor|PDL::Graphics::Prima::DataSet/ds::Pair> takes two arguments
1305 (the x-data and the y-data) and then key/value pairs that indicate
1306 your plotTypes and specify precisely how you want the data visualized:
1307  
1308 -scatter => ds::Pair($student_weights, $student_heights, ...options...)
1309  
1310 Typical x/y plots are plotted in such a way that the x-data is sorted in
1311 increasing order, but this is not required. This means that it is just as
1312 easy to draw a sine function as it is to draw a spiral or a scatter plot.
1313  
1314 L<Dists|PDL::Graphics::Prima::DataSet/Dist> take a single piddle of unordered
1315 data and visually represents it with aggregated plots like histograms,
1316 cumulative distributions, or curves to distribution fits. The
1317 L<constructor|PDL::Graphics::Prima::DataSet/ds::Dist> takes a
1318 single piddle argument that represents that data to plot, and then key/value
1319 pairs that let you tweak how the data is visualized. The most important
1320 key is the binning key, which dictates how the distribution should be mapped
1321 to pairwise data.
1322  
1323 -distribution => ds::Dist($student_heights,
1324 binning => bt::Log(min => 2),
1325 ...options...
1326 )
1327  
1328 Any pairwise plot type will work with the distribution plot types, but
1329 some make more (or less) sense than others. For example,
1330 L<CDFs|PDL::Graphics::Prima::DataSet/bt::CDF> are better visualized with
1331 lines whereas L<linearly binned data|PDL::Graphics::Prima::DataSet/bt::Linear>
1332 are sometimes better visualized with histograms.
1333  
1334 L<Func DataSets|PDL::Graphics::Prima::DataSet/Func> let you specify a function
1335 to plot, rather than forcing you to evaluate a specific function at fixed values
1336 of x. They inherit from L<Pairs|PDL::Graphics::Prima::DataSet/Pair> (in an OO
1337 sense) and differ in that the constructor expects a single function reference
1338 rather than two piddles of data:
1339  
1340 -model => ds::Func(\&my_model, ...options...)
1341  
1342 Because L<Func|PDL::Graphics::Prima::DataSet/Func> inherits from
1343 L<Pairs|PDL::Graphics::Prima::DataSet/Pair>, any
1344 L<Pairs PlotType|PDL::Graphics::Prima::PlotType/Pairs> will also work with
1345 a L<Func DataSet|PDL::Graphics::Prima::DataSet/Func>.
1346  
1347 The Grid DataSet is what you would use to visualize matrices or images. It
1348 takes a single piddle which represents a matrix of data,
1349 followed by key/value pairs the specify how you want the data plotted. In
1350 particular, there are many ways to specify the grid centers or boundaries.
1351  
1352 -terrain => ds::Grid($landscape, ...options...)
1353  
1354 The data that you specify for the Set, Pair, and Grid DataSets do not need
1355 to be piddles: anything that can be converted to a piddle, including scalar
1356 numbers and anonymous arrays of values, can be specified. That means that the
1357 following are valid DataSet specifications:
1358  
1359 -data => ds::Pair(sequence(10), sequence(10)->sin)
1360 -data => ds::Pair([1, 2, 3], [1, 4, 9])
1361 -data => ds::Pair(sequence(100), 5)
1362  
1363 Once you have specified the data or function that you want to plot, you can
1364 specify other options with key/value pairs. I discussed the
1365 plotType key already, but you can also specify any property in L<Prima::Drawable>.
1366 When you specify properties from L<Prima::Drawable>, these become the default
1367 parameters for all the plotTypes that belong to this DataSet. For example, you
1368 can specify a default color as C<cl::LightRed>, and then the lines, blobs, and
1369 error bars will be drawn in red unless they override the colors themselves.
1370 Function-based DataSets also recognize the C<N_points> key, which indicates the
1371 number of points to use in evaluating the function.
1372  
1373 To get an idea of how this works, suppose I have some data that I want to
1374 compare with a model. In this case, I would have two DataSets, the data (plotted
1375 using error bars) and the model (plotted using a line). I would plot all of this
1376 with code like so:
1377  
1378 plot(
1379 # The experimental data
1380 -data => ds::Pair(
1381 $x,
1382 $y,
1383 # I want error bars along with squares:
1384 plotTypes => [
1385 ppair::ErrorBars(y_err => $y_errors),
1386 ppair::Squares(filled => 1),
1387 ],
1388 ),
1389
1390 # The model:
1391 -model => ds::Func(
1392 \&my_model,
1393 # Default plotType is diamonds, but I want lines:
1394 plotType => ppair::Lines,
1395 lineStyle => lp::ShortDash,
1396 ),
1397 );
1398  
1399 The part C<< -data => ds::Pair(...) >> specifies the details for how you want to plot
1400 the experimental data and the part C<< -model >> specifies the details for how you
1401 want to plot the model.
1402  
1403 The DataSets are plotted in ASCIIbetical order, which means that in the example
1404 above, the model will be drawn over the error bars and squares. If you want the data
1405 plotted over the model curve, you should choose different names so that they sort
1406 the way you want. For example, using C<-curve> instead of C<-model> might work.
1407 So would changing the names from C<-data> and C<-model> to C<-b_data> and
1408 C<-a_model>, respectively.
1409  
1410 =head2 Plot Options
1411  
1412 Finally we come to setting plot-wide properties. As already discussed, you can
1413 disperse DataSets among your other Plot properties. Plot-wide properties include
1414 the title and the amount of room you want for the title (called titleSpace),
1415 the axis specifications, and any default L<Prima::Drawable> properties that you
1416 want applied to your plot.
1417  
1418 The text for your plot's title should be a simple Perl string. UTF8 characters
1419 are allowed, which means you can insert Greek or other symbols as you need them.
1420 However, L<Prima>, and therefore L<PDL::Graphics::Prima>, does not support fancy
1421 typesetting like subscripts or superscripts. (If you want that in the Plot
1422 library, you should probably consider petitioning for and helping add that
1423 functionality to Prima. Open-source is great like that!) The amount of space
1424 allocated for the title is currently set at 80 pixels. You can specify a
1425 different size if you prefer. (It should probably be calculated based on the
1426 current font-size---Prima makes it relatively easy to do that---but that's not
1427 yet implemented.) Space is allocated for the title only when you specify one;
1428 if none is specified, you have more room for your plot.
1429  
1430 Axis labels have similar restrictions and capabilities as the title string, but
1431 are properties of the axes themselves, which additionally have specifiable
1432 bounds (min and max) and scaling type. At the moment, the only two scaling types
1433 are C<sc::Linear> and C<sc::Log>. The bounds can be set to a specific numeric
1434 value, or to C<lm::Auto> if you want the bounds automatically computed based on
1435 your data and plotTypes.
1436  
1437 Finally, this is essentially a widget constructor, and as such you can specify
1438 any L<Prima::Widget> properties that you like. These include all the properties in
1439 L<Prima::Drawable>. For example, the default background color is white, because
1440 I like a white background on my plots. If you disagree, you can change the widget's
1441 background and foreground colors by specifying them. The DataSets and their
1442 plotTypes will inherit these properties (most importantly, the foreground color)
1443 and use them unless you override those properties seperately.
1444  
1445 =head2 Examples
1446  
1447 This first example is a simple line plot with triangles at each point. There's only
1448 one DataSet, and it has only two plotTypes:
1449  
1450 use strict;
1451 use warnings;
1452 use PDL::Graphics::Prima::Simple;
1453 use PDL;
1454
1455 my $x = sequence(100)/10;
1456 my $y = sin($x);
1457
1458 plot(
1459 -data => ds::Pair(
1460 $x,
1461 $y,
1462 plotTypes => [
1463 ppair::Triangles,
1464 ppair::Lines,
1465 ],
1466 ),
1467 );
1468  
1469 Now for something more fun. This figure uses bright colors and random circle radii.
1470 Notice that the lineWidth of 3 obscures many of the circles since their radii are
1471 between 1 and 5. This has only one DataSet and two plotTypes like the
1472 previous example. In contrast to the previous example, it specifies a number of
1473 properties for the plotTypes:
1474  
1475 use strict;
1476 use warnings;
1477 use PDL::Graphics::Prima::Simple;
1478 use PDL;
1479
1480 my $x = sequence(100)/10;
1481 my $y = sin($x);
1482 my $colors = pal::Rainbow->apply($y);
1483
1484 plot(
1485 -data => ds::Pair(
1486 $x,
1487 $y,
1488 plotTypes => [
1489 ppair::Blobs (
1490 radius => 1 + $x->random*4,
1491 colors => $colors,
1492 ),
1493 ppair::Lines (
1494 lineWidths => 3,
1495 ),
1496 ],
1497 ),
1498 );
1499  
1500 Here I use a black background and white foreground, and plot the circles B<over>
1501 the line instead of under it. I achieve this by changing the order of the
1502 plotTypes---Lines then Blobs.
1503  
1504 use strict;
1505 use warnings;
1506 use PDL::Graphics::Prima::Simple;
1507 use PDL;
1508
1509 my $x = sequence(100)/10;
1510 my $y = sin($x);
1511 my $colors = pal::Rainbow->apply($y);
1512 my $radius = 1 + $x->random*4;
1513
1514 plot(
1515 -data => ds::Pair(
1516 $x,
1517 $y,
1518 plotTypes => [
1519 ppair::Lines (
1520 lineWidths => 3,
1521 ),
1522 ppair::Blobs (
1523 radius => $radius,
1524 colors => $colors,
1525 ),
1526 ],
1527 ),
1528 backColor => cl::Black,
1529 color => cl::White,
1530 );
1531  
1532 I find the smaller points very difficult to see, so here's a version in which I
1533 'wrap' the points with a white radius. I also use the Symbols plotType instead
1534 of the Blobs plotType because it's a bit more flexible:
1535  
1536 use strict;
1537 use warnings;
1538 use PDL::Graphics::Prima::Simple;
1539 use PDL;
1540
1541 my $x = sequence(100)/10;
1542 my $y = sin($x);
1543 my $colors = pal::Rainbow->apply($y);
1544 my $radius = 1 + $x->random*4;
1545
1546 plot(
1547 -data => ds::Pair(
1548 $x,
1549 $y,
1550 plotTypes => [
1551 ppair::Lines (
1552 lineWidths => 3,
1553 ),
1554 ppair::Symbols(
1555 size => 1 + $radius,
1556 filled => 'no',
1557 N_points => 0,
1558 ),
1559 ppair::Symbols (
1560 size => $radius,
1561 colors => $colors,
1562 filled => 'yes',
1563 N_points => 0,
1564 ),
1565 ],
1566 ),
1567 backColor => cl::Black,
1568 color => cl::White,
1569 );
1570  
1571 Here I use PDL threading to achieve the same ends as the previous example, but
1572 only using one Blobs plotType instead of two.
1573  
1574 use strict;
1575 use warnings;
1576 use PDL::Graphics::Prima::Simple;
1577 use PDL;
1578
1579 my $x = sequence(100)/10;
1580 my $y = sin($x);
1581 my $rainbow_colors = pal::Rainbow->apply($y);
1582 my $whites = $y->ones * cl::White;
1583 my $colors = cat($whites, $rainbow_colors);
1584 my $inner_radius = 1 + $x->random*4;
1585 my $radius = cat($inner_radius + 1, $inner_radius);
1586
1587 plot(
1588 -data => ds::Pair(
1589 $x,
1590 $y,
1591 plotTypes => [
1592 ppair::Lines (
1593 lineWidths => 3,
1594 ),
1595 ppair::Blobs(
1596 radius => $radius,
1597 colors => $colors,
1598 ),
1599 ],
1600 ),
1601 backColor => cl::Black,
1602 color => cl::White,
1603 );
1604  
1605 Here I generate some linear data with noise and perform a least-squares fit to
1606 it. In this case I perform the least-squares fit by hand, since not everybody
1607 will have Slatec installed. The important part is the C<use PDL::Graphics::Prima::Simple>
1608 line and beyond.
1609  
1610 This example demonstrates the use of multiple data sets, the use of the
1611 ErrorBars plotType and the use of function-based data sets.
1612  
1613 use strict;
1614 use warnings;
1615 use PDL;
1616
1617 my $x = sequence(100)/10;
1618 my $y = $x/2 - 3 + $x->grandom*3;
1619 my $y_err = 2*$x->grandom->abs + 1;
1620
1621 # Calculate the slope and intercept:
1622 my $S = sum(1/$y_err);
1623 my $S_x = sum($x/$y_err);
1624 my $S_y = sum($y/$y_err);
1625 my $S_xx = sum($x*$x/$y_err);
1626 my $S_xy = sum($x*$y/$y_err);
1627 my $slope = ($S_xy * $S - $S_x * $S_y) / ($S_xx * $S - $S_x * $S_x);
1628 my $y0 = ($S_xy - $slope * $S_xx) / $S_x;
1629
1630
1631 use PDL::Graphics::Prima::Simple;
1632
1633 plot(
1634 -data => ds::Pair(
1635 $x,
1636 $y,
1637 plotTypes => [
1638 ppair::Diamonds(filled => 'yes'),
1639 ppair::ErrorBars(y_err => $y_err),
1640 ],
1641 ),
1642 -func => ds::Func(
1643 sub { $y0 + $slope * $_[0] },
1644 lineWidth => 2,
1645 color => cl::LightRed,
1646 ),
1647 );
1648  
1649 That example used a function-based DataSet, but we could just as easily have
1650 used C<ppair::TrendLines> to compute the fit for us. The only difference between
1651 the last example and the one below is that the trendline for this next example
1652 does not extend out to infinity in the x-direction but terminates at the
1653 end of the data.
1654  
1655 use strict;
1656 use warnings;
1657 use PDL;
1658
1659 my $x = sequence(100)/10;
1660 my $y = $x/2 - 3 + $x->grandom*3;
1661 my $y_err = 2*$x->grandom->abs + 1;
1662
1663 use PDL::Graphics::Prima::Simple;
1664
1665 plot(
1666 -data => ds::Pair(
1667 $x,
1668 $y,
1669 plotTypes => [
1670 ppair::Diamonds(filled => 'yes'),
1671 ppair::ErrorBars(y_err => $y_err),
1672 ppair::TrendLines(
1673 weights => $y_err,
1674 lineWidths => 2,
1675 colors => cl::LightRed,
1676 ),
1677 ],
1678 ),
1679 );
1680  
1681  
1682 You can extend the Simple interface with GUI methods. The next example gives
1683 you a first glimps into GUI-flavored programming by overriding the onMouseMove
1684 method for this Prima widget. There are many ways of setting, overriding, or
1685 adding callbacks in relation to all sorts of GUI events, but when using the
1686 C<plot> command, your only option is to specify it as OnEventName.
1687  
1688 In this example, I add (that's B<add>, not override, becaus Prima rocks) a
1689 method that prints out the mouse position to the console. I also use logarithmic
1690 scaling in the x direction (and specify x- and y-axes labels) to make things
1691 interesting:
1692  
1693 use strict;
1694 use warnings;
1695 use PDL::Graphics::Prima::Simple;
1696 use PDL;
1697
1698 # Turn on autoflush:
1699 $|++;
1700
1701 my $x = sequence(100)/10 + 1;
1702 my $y = sin($x);
1703
1704 plot(
1705 -data => ds::Pair(
1706 $x,
1707 $y,
1708 plotTypes => [
1709 ppair::Xs,
1710 ppair::Lines,
1711 ],
1712 ),
1713 onMouseMove => sub {
1714 # Get the widget and the coordinates:
1715 my ($self, $button_and_modifier, $x_pixel, $y_pixel) = @_;
1716 # Convert the pixel coordinates to real values:
1717 my $x = $self->x->pixels_to_reals($x_pixel);
1718 my $y = $self->y->pixels_to_reals($y_pixel);
1719 # Print the results:
1720 print "\r($x, $y) ";
1721 },
1722 x => {
1723 label => 'time (s)',
1724 scaling => sc::Log,
1725 },
1726 y => {
1727 label => 'displacement (m)',
1728 }
1729 );
1730  
1731 This kind of immediate feedback can be very useful. It is even possible to
1732 capture keyboard events and respond to user interaction this way. But B<please>,
1733 don't do that. If you need any substantial amount of user interaction, you
1734 would do much better to learn to create a Prima application with buttons, lists,
1735 and input lines, along with the Plot widget. For that, see the (soon to be
1736 written) L<PDL::Graphics::Prima::InteractiveTut>.
1737  
1738 =cut
1739  
1740 # A function that allows for quick one-off plots by packing a plot widget
1741 # into a window. In void context and no readline support, it builds and
1742 # executes the window. In void context and readline support it returns
1743 # immediately, letting the readline handle yield()ing. A scalar context
1744 # return is only allowed when readline support is enabled. (App::Prima::REPL
1745 # allows for scalar return context by overriding this plot command, and other
1746 # libraries that want to support the simple interface should do the same.)
1747 # In list context, it returns both the window and the plot object.
1748  
1749 # A function that allows for quick one-off plots:
1750 *plot = \&default_plot;
1751 our $auto_twiddling = 1;
1752 our $is_twiddling = 0;
1753 our $N_windows = 0;
1754 sub default_plot {
1755 # Make sure they sent key/value pairs:
1756 croak("Arguments to plot must be in key => value pairs")
1757 unless @_ % 2 == 0;
1758 my %args = @_;
1759
1760 # Create a new window and pack the plot into said window
1761 unless (defined $::application) {
1762 require Prima::Application;
1763 Prima::Application->import;
1764 }
1765 my $window = Prima::Window->create(
1766 text => $args{title} || 'PDL::Graphics::Prima',
1767 size => $args{size} || [our @default_sizes],
1768 # Add a stop-twiddling listener
1769 onKeyDown => sub {
1770 my (undef, $key) = @_;
1771 $is_twiddling = 0 if chr($key) =~ /q/i;
1772 },
1773 # Pair of functions to note when windows are created and destroyed
1774 # for purposes of quitting twiddling when the last window is closed.
1775 onCreate => sub {
1776 $N_windows++;
1777 },
1778 onDestroy => sub {
1779 $N_windows--;
1780 $is_twiddling = 0 if $N_windows == 0;
1781 },
1782 );
1783 my $plot = $window->insert('Plot',
1784 pack => { fill => 'both', expand => 1},
1785 %args
1786 );
1787 $plot->onKeyDown(sub {
1788 my (undef, $key) = @_;
1789 $is_twiddling = 0 if chr($key) =~ /q/i;
1790 });
1791 # make sure it shows up on top.
1792 $window->bring_to_front;
1793
1794 # Twiddle, then return. Note that twiddling (defined below) may be a
1795 # no-op for configurations where the application loop is already running.
1796 twiddle() if $auto_twiddling;
1797 return $plot;
1798 }
1799  
1800 sub auto_twiddle {
1801 $auto_twiddling = $_[0] if @_;
1802 return $auto_twiddling;
1803 }
1804  
1805 # Make twiddling a no-op if we're in the perldl shell and have event_loop
1806 # support:
1807 use Scalar::Util qw(refaddr);
1808 if (PDL::Graphics::Prima::ReadLine->is_setup) {
1809 *twiddle = sub {};
1810 }
1811 # Otherwise, make it run the event loop:
1812 else {
1813 *twiddle = sub {
1814 # twiddling should be a no-op if the plot function is not default_plot,
1815 # which is the case for App::Prima::REPL
1816 return if refaddr(\&plot) != refaddr(\&default_plot);
1817
1818 # No event looping if we don't have any open windows. Otherwise,
1819 # they won't be able to exit the loop!
1820 print "No open plots\n" and return if $N_windows == 0;
1821 # Print a notice explaining what's going on:
1822 print "Twiddling plot; close window or press q or Q to resume\n";
1823
1824 # We will use Prima's nice exception handling to exit the go()
1825 # method. In order to prevent undue error propogation, localize
1826 # the error message:
1827 local $@;
1828
1829 $is_twiddling = 1;
1830 # Start the timer that will check for the exit condition. There
1831 # are a number of ways in which the loop will want to exit; placing
1832 # the exit excption here centralizes the exception handling.
1833 Prima::Timer->create(
1834 onTick => sub {
1835 if (not $is_twiddling) {
1836 $_[0]->stop;
1837 # die in order to exit the application loop
1838 die 'done with event loop';
1839 }
1840 },
1841 timeout => 500, # milliseconds
1842 )->start;
1843 # Run go() in an eval so we catch the exit exception
1844 eval { $::application->go };
1845 # Rethrow the error unless it was the exit exception
1846 die unless $@ =~ /^done with event loop/;
1847 };
1848 }
1849 # Add the twiddle method to the Prima window
1850 *Prima::Window::twiddle = \&twiddle;
1851 *Prima::Plot::twiddle = \&twiddle;
1852  
1853  
1854 =head1 IMPORTED METHODS
1855  
1856 There are a couple of ways to call this module. The first is just a simple
1857 use statement:
1858  
1859 use PDL::Graphics::Prima::Simple;
1860  
1861 This will import the above mentioned functions into your local package's
1862 symbol table, which is generally what you want. If you do not want any
1863 functions imported, you can call it with an empty string:
1864  
1865 use PDL::Graphics::Prima::Simple '';
1866  
1867 or you can name the functions that you want imported:
1868  
1869 use PDL::Graphics::Prima::Simple qw(plot);
1870  
1871 In addition, you can specify the default window plot size by passing a two
1872 element anonymous array:
1873  
1874 # default to 800 x 800 window:
1875 use PDL::Graphics::Prima::Simple [800, 800];
1876
1877 # default to 800 wide by 600 tall, import nothing:
1878 use PDL::Graphics::Prima::Simple [800, 600], '';
1879
1880 # default to 300 wide by 450 tall, import 'plot' function:
1881 use PDL::Graphics::Prima::Simple [300, 450], 'plot';
1882  
1883 As an experimental feature, you can provide a subroutine reference in
1884 the import method. This subroutine reference will get invoked by the
1885 plotting commands instead of the default plotting mechanism. This is of
1886 marginal utility, and might be better achieved with a simple glob assignment
1887 of C<*PDL::Graphics::Prima::Simple::plot> to your desired function. The glob
1888 assignment has the advantage that it can be C<local>ized.
1889  
1890 Note: I am considering adding a '-hold' option, which would cause all
1891 void-context plot commands in scripts to not block, and cause the Prima
1892 event loop to be run at the end of the script. However, I haven't settled
1893 on either the behavior or the name. Input is welcome!
1894  
1895 =cut
1896  
1897 # import/export stuff:
1898 require Exporter;
1899 our @ISA = qw(Exporter);
1900 our @EXPORT = qw(plot line_plot circle_plot triangle_plot
1901 square_plot diamond_plot cross_plot X_plot asterisk_plot hist_plot
1902 matrix_plot imag_plot func_plot
1903 twiddle auto_twiddle
1904 );
1905 our @EXPORT_OK = (@EXPORT);
1906  
1907 our @default_sizes = (400, 400);
1908  
1909 # Override the import method to handle a few user-specifiable arguments:
1910 sub import {
1911 my $package = shift;
1912 my @args;
1913 # Run through all the arguments and pull out anything special:
1914 foreach my $arg (@_) {
1915 # See if they passed in an array reference
1916 if(ref ($arg) and ref($arg) eq 'ARRAY') {
1917 # Make sure it is the correct size:
1918 croak("Array references passed to PDL::Graphics::Prima::Simple indicate the\n"
1919 . "desired plot window size and must contain two elements")
1920 unless @$arg == 2;
1921
1922 # Apparently we're good to go so save the sizes:
1923 @default_sizes = @$arg;
1924 }
1925 #elsif ($arg eq '-hold') {
1926 # # Add code here for holding after each plot
1927 #}
1928 elsif (ref ($arg) and ref($arg) eq 'CODE') {
1929 # a CODE ref; assign plot() to it
1930 no warnings 'redefine';
1931 *plot = $arg;
1932 }
1933 else {
1934 push @args, $arg;
1935 }
1936 }
1937
1938 $package->export_to_level(1, $package, @args);
1939 }
1940  
1941 1;
1942  
1943 __END__