-
Notifications
You must be signed in to change notification settings - Fork 0
/
gnuplotlib.py
1776 lines (1277 loc) · 69 KB
/
gnuplotlib.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
r'''a gnuplot-based plotting backend for numpy
* SYNOPSIS
import numpy as np
import gnuplotlib as gp
x = np.arange(101) - 50
gp.plot(x**2)
[ basic parabola plot pops up ]
g1 = gp.gnuplotlib(title = 'Parabola with error bars',
_with = 'xyerrorbars')
g1.plot( x**2 * 10, np.abs(x)/10, np.abs(x)*5,
legend = 'Parabola',
tuplesize = 4 )
[ parabola with x,y errobars pops up in a new window ]
x,y = np.ogrid[-10:11,-10:11]
gp.plot( x**2 + y**2,
title = 'Heat map',
unset = 'grid',
cmds = 'set view map',
_with = 'image',
tuplesize = 3)
[ Heat map pops up where first parabola used to be ]
theta = np.linspace(0, 6*np.pi, 200)
z = np.linspace(0, 5, 200)
g2 = gp.gnuplotlib(_3d = True)
g2.plot( np.cos(theta),
np.vstack((np.sin(theta), -np.sin(theta))),
z )
[ Two 3D spirals together in a new window ]
* DESCRIPTION
This module allows numpy data to be plotted using Gnuplot as a backend. As much
as was possible, this module acts as a passive pass-through to Gnuplot, thus
making available the full power and flexibility of the Gnuplot backend. Gnuplot
is described in great detail at its upstream website: http://www.gnuplot.info
gnuplotlib has an object-oriented interface (via class gnuplotlib) and a few
helper class-less functions (plot(), plot3d(), plotimage()). Each instance of
class gnuplotlib has a gnuplot process associated with it, which has (usually) a
plot window to go with it. If multiple simultaneous plot windows are desired,
create a separate class gnuplotlib object for each.
The helper functions reuse a single global gnuplotlib instance, so each such
invocation rewrites over the previous gnuplot window.
When making a plot with the object-oriented interface, the gnuplotlib object is
created with a set of plot options, then the plot is made by passing it curves,
possibly with some curve options per curve. Something like this:
import gnuplotlib as gp
g = gp.gnuplotlib(plot_options)
g.plot( curve, curve, .... )
A call to plot(...) is simpler:
import gnuplotlib as gp
gp.plot( curve, curve, ...., plot_and_default_curve_options )
plot3d(...) simply calls plot(...) with an extra plot option _3d=True.
plotimage(...) simply calls plot(...) with extra plot options _with='image',
tuplesize=3.
If just a single curve is plotted, 'curve' can simply be a sequence of numpy
arrays representing coordinates of each point. For instance:
plot( x, y )
If multiple curves are to be drawn on the same plot, then each 'curve' must live
in a separate tuple. The last element of any such tuple can be a dict of curve
options, if desired. For instance:
plot( (x1,y1),
(x2,y2, {'legend': 'Second curve'}) )
The plot_and_default_curve_options passed to plot(...) are kwargs. The curve
options present here are used as defaults for each curve; these defaults can be
overriden as desired. For instance:
plot( (x1,y1),
(x2,y2, {'with':'points'}),
_with='lines')
would plot the first curve with lines, but the second with points.
** Options arguments
Plot generation is controlled by two sets of options:
- Plot options: parameters that affect the whole plot, like the title of the
plot, the axis labels, the extents, 2d/3d selection, etc. All the plot options
are described below in "Plot options".
- Curve options: parameters that affect only a single curve. Each is described
below in "Curve options".
** Data arguments
The 'curve' arguments in the plot(...) argument list represent the actual data
being plotted. Each output data point is a tuple (set of values, not a python
"tuple") whose size varies depending on what is being plotted. For example if
we're making a simple 2D x-y plot, each tuple has 2 values; if we're making a 3d
plot with each point having variable size and color, each tuple has 5 values
(x,y,z,size,color). In the plot(...) argument list each tuple element must be
passed separately. If we're making anything fancier than a simple 2D or 3D plot
(2- and 3- tuples respectively) then the 'tuplesize' curve option MUST be passed
in.
Furthermore, broadcasting is fully supported, so multiple curves can be plotted
by stacking data inside the passed-in arrays. Broadcasting works across curve
options also, so things like curve labels and styles can also be stacked inside
arrays. An example:
th = np.linspace(0, 6*np.pi, 200)
z = np.linspace(0, 5, 200)
size = 0.5 + np.abs(np.cos(th))
color = np.sin(2*th)
# without broadcasting:
plot3d( ( np.cos(th), np.sin(th)
z, size, color,
{ 'legend': 'spiral 1'}),
( -np.cos(th), -np.sin(th)
z, size, color,
{ 'legend': 'spiral 2'})
title = 'double helix', tuplesize = 5,
_with = 'points pointsize variable pointtype 7 palette' )
# identical plot using broadcasting:
plot3d( ( np.cos(th) * np.array([[1,-1]]).T,
np.sin(th) * np.array([[1,-1]]).T,
z, size, color, { 'legend': np.array(('spiral 1', 'spiral 2'))})
title = 'double helix', tuplesize = 5,
_with = 'points pointsize variable pointtype 7 palette' )
This is a 3d plot with variable size and color. There are 5 values in the tuple,
which we specify. The first 2 arrays have dimensions (2,N); all the other arrays
have a single dimension. Thus the broadcasting rules generate 2 distinct curves,
with varying values for x,y and identical values for z, size and color. We label
the curves differently by passing an array for the 'legend' curve option. This
array contains strings, and is broadcast like everything else.
*** Implicit domains
When a particular tuplesize is specified, gnuplotlib will attempt to read that
many arrays. If there aren't enough arrays available, gnuplotlib will throw an
error, unless an implicit domain can be used. This happens if we are EXACTLY 1
or 2 arrays short (usually when making 2D and 3D plots respectively).
When making a simple 2D plot, if exactly 1 dimension is missing, gnuplotlib will
use numpy.arange(N) as the domain. This is why code like
plot(numpy.array([1,5,3,4,4]))
works. Only one array is given here, but the default tuplesize is 2, and we are
thus exactly 1 array short. This is thus equivalent to
plot(numpy.arange(5), numpy.array([1,5,3,4,4]) )
If plotting in 3D, an implicit domain will be used if we are exactly 2 arrayss
short. In this case, gnuplotlib will use a 2D grid as a domain. Example:
xy = numpy.arange(21*21).reshape(21*21)
plot( xy, _with = 'points', _3d=True)
Here the only given array has dimensions (21,21). This is a 3D plot, so we are
exactly 2 arrays short. Thus, gnuplotlib generates an implicit domain,
corresponding to a 21-by-21 grid.
Note that while the DEFAULT tuplesize depends on whether we're making a 3d plot,
once we have a tuplesize, the logic doesn't care if a 3d plot is being made. It
can make sense to have a 2D implicit domain when making 2D plots. For example,
one can be plotting a color map:
x,y = np.ogrid[-10:11,-10:11]
gp.plot( x**2 + y**2,
title = 'Heat map',
set = 'view map',
_with = 'image',
tuplesize = 3)
Also note that the 'tuplesize' curve option is independent of implicit domains.
This option specifies not how many data arrays we have, but how many values
represent each data point. For example, if we want a 2D line plot with varying
colors plotted with an implicit domain, set tuplesize=3 as before (x,y,color),
but pass in only 2 arrays (y, color).
** Symbolic equations
Gnuplot can plot both data and equations. This module exists largely for the
data-plotting case, but sometimes it can be useful to plot equations together
with some data. This is supported by the 'equation' plot option. This plot
option is either a string (for a single equation) or a list/tuple containing
multiple strings for multiple equations. Note that plotting only equations
without data is not supported (and generally is better done with gnuplot
directly). An example:
import numpy as np
import numpy.random as nr
import numpy.linalg
import gnuplotlib as gp
# generate data
x = np.arange(100)
c = np.array([1, 1800, -100, 0.8]) # coefficients
m = x[:, np.newaxis] ** np.arange(4) # 1, x, x**2, ...
noise = 1e4 * nr.random(x.shape)
y = np.dot( m, c) + noise # polynomial corrupted by noise
c_fit = np.dot(numpy.linalg.pinv(m), y) # coefficients obtained by a curve fit
# generate a string that describes the curve-fitted equation
fit_equation = '+'.join( '{} * {}'.format(c,m) for c,m in zip( c_fit.tolist(), ('x**0','x**1','x**2','x**3')))
# plot the data points and the fitted curve
gp.plot(x, y, _with='points', equation = fit_equation)
Here I generated some data, performed a curve fit to it, and plotted the data
points together with the best-fitting curve. Here the best-fitting curve was
plotted by gnuplot as an equation, so gnuplot was free to choose the proper
sampling frequency. And as we zoom around the plot, the sampling frequency is
adjusted to keep things looking nice.
Note that the various styles and options set by the other options do NOT apply
to these equation plots. Instead, the string is passed to gnuplot directly, and
any styling can be applied there. For instance, to plot a parabola with thick
lines, you can issue
gp.plot( ....., equation = 'x**2 with lines linewidth 2')
As before, see the gnuplot documentation for details. You can also do fancy
things:
x = np.arange(100, dtype=float) / 100 * np.pi * 2;
c,s = np.cos(x), np.sin(x)
gp.plot( c,s,
square=1, _with='points',
set = ('parametric', 'trange [0:2*3.14]'),
equation = "sin(t),cos(t)" )
Here the data are points evently spaced around a unit circle. Along with these
points we plot a unit circle as a parametric equation.
** Interactivity
The graphical backends of Gnuplot are interactive, allowing the user to pan,
zoom, rotate and measure the data in the plot window. See the Gnuplot
documentation for details about how to do this. Some terminals (such as wxt) are
persistently interactive, and the rest of this section does not apply to them.
Other terminals (such as x11) have the downside described here.
When using an affected terminal, interactivity is only possible if the gnuplot
process is running. As long as the python program calling gnuplotlib is running,
the plots are interactive, but once it exits, the child gnuplot process will
exit also. This will keep the plot windows up, but the interactivity will be
lost. So if the python program makes a plot and exits, the plot will NOT be
interactive.
* OPTIONS
** Plot options
The plot options are a dictionary, passed as the keyword arguments to the global
plot() function or as the only arguments to the gnuplotlib contructor. The
supported keys of this dict are as follows:
- title
Specifies the title of the plot
- 3d
If true, a 3D plot is constructed. This changes the default tuple size from 2 to
3
- _3d
Identical to '3d'. In python, keyword argument keys cannot start with a number,
so '_3d' is accepted for that purpose. Same issue exists with with/_with
- set/unset
These take either a string of a list. If given a string, a set or unset gnuplot
command is executed with that argument. If given a list, elements of that list
are set/unset separately. Example:
plot(..., set='grid', unset=['xtics', 'ytics])
[ turns on the grid, turns off the x and y axis tics ]
- with
If no 'with' curve option is given, use this as a default. See the description
of the 'with' curve option for more detail
- _with
Identical to 'with'. In python 'with' is a reserved word so it is illegal to use
it as a keyword arg key, so '_with' exists as an alias. Same issue exists with
3d/_3d
- square, square_xy
If true, these request a square aspect ratio. For 3D plots, square_xy plots with
a square aspect ratio in x and y, but scales z. Using either of these in 3D
requires Gnuplot >= 4.4
- {x,y,y2,z,cb}{min,max,range,inv}
If given, these set the extents of the plot window for the requested axes.
Either min/max or range can be given but not both. min/max are numerical values.
'*range' is a string 'min:max' with either one allowed to be omitted; it can
also be a [min,max] tuple or list. '*inv' is a boolean that reverses this axis.
If the bounds are known, this can also be accomplished by setting max < min.
The y2 axis is the secondary y-axis that is enabled by the 'y2' curve option.
The 'cb' axis represents the color axis, used when color-coded plots are being
generated
- xlabel, ylabel, zlabel, y2label
These specify axis labels
- equation
This option allows equations represented as formula strings to be plotted along
with data passed in as numpy arrays. This can be a string (for a single
equation) or an array/tuple of strings (for multiple equations). See the
"Symbolic equations" section above.
- hardcopy
Instead of drawing a plot on screen, plot into a file instead. The output
filename is the value associated with this key. The output format is inferred
from the filename. Currently only eps, ps, pdf, png, svg are supported with some
default sets of options. This option is simply a shorthand for the 'terminal'
and 'output' options. If the defaults provided by the 'hardcopy' option are
insufficient, use 'terminal' and 'output' manually. Example:
plot(..., hardcopy="plot.pdf")
[ Plots into that file ]
- terminal
Selects the gnuplot terminal (backend). This determines how Gnuplot generates
its output. Common terminals are 'x11', 'qt', 'pdf', 'dumb' and so on. See the
Gnuplot docs for all the details.
- output
Sets the plot output file. You generally only need to set this if you're
generating a hardcopy, such as a PDF.
There are several gnuplot terminals that are known (at this time) to be
interactive: "x11", "qt" and so on. For these no "output" setting is desired.
For noninteractive terminals ("pdf", "dumb" and so on) the output will go to the
file defined here. If this plot option isn't defined or set to the empty string,
the output will be redirected to the standard output of the python process
calling gnuplotlib.
>>> gp.plot( np.linspace(-5,5,30)**2,
... unset='grid', terminal='dumb 80 40' )
25 A-+---------+-----------+-----------+----------+-----------+---------A-+
* + + + + + * +
|* * |
|* * |
| * * |
| A A |
| * * |
20 +-+ * * +-+
| * * |
| A A |
| * * |
| * * |
| * * |
| A A |
15 +-+ * * +-+
| * * |
| * * |
| A A |
| * * |
| * * |
| A A |
10 +-+ * * +-+
| * * |
| A A |
| * * |
| * * |
| A A |
| * * |
5 +-+ A A +-+
| * ** |
| A** A |
| * |
| A* *A |
| A* *A |
+ + + A** + *A* + + +
0 +-+---------+-----------+------A*A**A*A--------+-----------+---------+-+
0 5 10 15 20 25 30
- cmds
Arbitrary extra commands to pass to gnuplot before the plots are created. These
are passed directly to gnuplot, without any validation. The value is either a
string of a list of strings, one per command
- dump
Used for debugging. If true, writes out the gnuplot commands to STDOUT instead
of writing to a gnuplot process. Useful to see what commands would be sent to
gnuplot. This is a dry run. Note that this dump will contain binary data unless
ascii-only plotting is enabled (see below). This is also useful to generate
gnuplot scripts since the dumped output can be sent to gnuplot later, manually
if desired.
- log
Used for debugging. If true, writes out the gnuplot commands and various
progress logs to STDERR in addition to writing to a gnuplot process. This is NOT
a dry run: data is sent to gnuplot AND to the log. Useful for debugging I/O
issues. Note that this log will contain binary data unless ascii-only plotting
is enabled (see below)
- ascii
If set, ASCII data is passed to gnuplot instead of binary data. Binary is the
default because it is much more efficient (and thus faster). Binary input works
for most plots, but not for all of them. An example where binary plotting
doesn't work is 'with labels', and this option exists to force ASCII
communication
** Curve options
The curve options describe details of specific curves. They are in a dict, whose
keys are as follows:
- legend
Specifies the legend label for this curve
- with
Specifies the style for this curve. The value is passed to gnuplot using its
'with' keyword, so valid values are whatever gnuplot supports. Read the gnuplot
documentation for the 'with' keyword for more information
- _with
Identical to 'with'. In python 'with' is a reserved word so it is illegal to use
it as a keyword arg key, so '_with' exists as an alias
- y2
If true, requests that this curve be plotted on the y2 axis instead of the main y axis
- tuplesize
Specifies how many values represent each data point. For 2D plots this defaults
to 2; for 3D plots this defaults to 3. These defaults are correct for simple
plots
* INTERFACE
** class gnuplotlib
A gnuplotlib object abstracts a gnuplot process and a plot window. Invocation:
import gnuplotlib as gp
g = gp.gnuplotlib(plot_options)
g.plot( curve, curve, .... )
The plot options are passed into the constructor; the curve options and the data
are passed into the plot() method. One advantage of making plots this way is
that there's a gnuplot process associated with each gnuplotlib instance, so as
long as the object exists, the plot will be interactive. Calling 'g.plot()'
multiple times reuses the plot window instead of creating a new one.
** global plot(...)
The convenience plotting routine in gnuplotlib. Invocation:
import gnuplotlib as gp
gp.plot( curve, curve, ...., plot_and_default_curve_options )
Each 'plot()' call reuses the same window.
** global plot3d(...)
Generates 3D plots. Shorthand for 'plot(..., _3d=True)'
** global plotimage(...)
Generates an image plot. Shorthand for 'plot(..., _with='image', tuplesize=3)'
* RECIPES
Some different plots appear here. A longer set of demos is given in demos.py.
** 2D plotting
If we're plotting y-values sequentially (implicit domain), all you need is
plot(y)
If we also have a corresponding x domain, we can plot y vs. x with
plot(x, y)
*** Simple style control
To change line thickness:
plot(x,y, _with='lines linewidth 3')
To change point size and point type:
gp.plot(x,y, _with='points pointtype 4 pointsize 8')
Everything (like _with) feeds directly into Gnuplot, so look at the Gnuplot docs
to know how to change thicknesses, styles and such.
*** Errorbars
To plot errorbars that show y +- 1, plotted with an implicit domain
plot( y, np.ones(y.shape), _with = 'yerrorbars', tuplesize = 3 )
Same with an explicit x domain:
plot( x, y, np.ones(y.shape), _with = 'yerrorbars', tuplesize = 3 )
Symmetric errorbars on both x and y. x +- 1, y +- 2:
plot( x, y, np.ones(x.shape), 2*np.ones(y.shape), _with = 'xyerrorbars', tuplesize = 4 )
To plot asymmetric errorbars that show the range y-1 to y+2 (note that here you
must specify the actual errorbar-end positions, NOT just their deviations from
the center; this is how Gnuplot does it)
plot( y, y - np.ones(y.shape), y + 2*np.ones(y.shape),
_with = 'yerrorbars', tuplesize = 4 )
*** More multi-value styles
Plotting with variable-size circles (size given in plot units, requires Gnuplot >= 4.4)
plot(x, y, radii,
_with = 'circles', tuplesize = 3)
Plotting with an variably-sized arbitrary point type (size given in multiples of
the "default" point size)
plot(x, y, sizes,
_with = 'points pointtype 7 pointsize variable', tuplesize = 3 )
Color-coded points
plot(x, y, colors,
_with = 'points palette', tuplesize = 3 )
Variable-size AND color-coded circles. A Gnuplot (4.4.0) quirk makes it
necessary to specify the color range here
plot(x, y, radii, colors,
cbmin = mincolor, cbmax = maxcolor,
_with = 'circles palette', tuplesize = 4 )
Broadcasting example: the Conchoids of de Sluze. The whole family of curves is
generated all at once, and plotted all at once with broadcasting. Broadcasting
is also used to generate the labels. Generally these would be strings, but here
just printing the numerical value of the parameter is sufficient.
theta = np.linspace(0, 2*np.pi, 1000) # dim=( 1000,)
a = np.arange(-4,3)[:, np.newaxis] # dim=(7,1)
gp.plot( theta,
1./np.cos(theta) + a*np.cos(theta), # broadcasted. dim=(7,1000)
_with = 'lines',
set = 'polar',
square = True,
yrange = [-5,5],
legend = a.ravel() )
** 3D plotting
General style control works identically for 3D plots as in 2D plots.
To plot a set of 3d points, with a square aspect ratio (squareness requires
Gnuplot >= 4.4):
plot3d(x, y, z, square = 1)
If xy is a 2D array, we can plot it as a height map on an implicit domain
plot3d(xy)
Ellipse and sphere plotted together, using broadcasting:
th = np.linspace(0, np.pi*2, 30)
ph = np.linspace(-np.pi/2, np.pi*2, 30)[:,np.newaxis]
x_3d = (np.cos(ph) * np.cos(th)) .ravel()
y_3d = (np.cos(ph) * np.sin(th)) .ravel()
z_3d = (np.sin(ph) * np.ones( th.shape )) .ravel()
gp.plot3d( (x_3d * np.array([[1,2]]).T,
y_3d * np.array([[1,2]]).T,
z_3d,
{ 'legend': np.array(('sphere', 'ellipse'))}),
title = 'sphere, ellipse',
square = True,
_with = 'points')
Image arrays plots can be plotted as a heat map:
x,y = np.ogrid[-10:11,-10:11]
gp.plot( x**2 + y**2,
title = 'Heat map',
set = 'view map',
_with = 'image',
tuplesize = 3)
** Hardcopies
To send any plot to a file, instead of to the screen, one can simply do
plot(x, y,
hardcopy = 'output.pdf')
The 'hardcopy' option is a shorthand for the 'terminal' and 'output'
options. If more control is desired, the latter can be used. For example to
generate a PDF of a particular size with a particular font size for the text,
one can do
plot(x, y,
terminal = 'pdfcairo solid color font ",10" size 11in,8.5in',
output = 'output.pdf')
This command is equivalent to the 'hardcopy' shorthand used previously, but the
fonts and sizes can be changed.
'''
import subprocess
import time
import sys
import os
import re
import select
import numpy as np
import numpysane as nps
# note that 'with' is both a known plot and curve option
knownPlotOptions = frozenset(('3d', 'dump', 'ascii', 'log',
'cmds', 'set', 'unset', 'square', 'square_xy', 'title',
'hardcopy', 'terminal', 'output',
'with', 'equation',
'xmax', 'xmin', 'xrange', 'xinv', 'xlabel',
'y2max', 'y2min', 'y2range', 'y2inv', 'y2label',
'ymax', 'ymin', 'yrange', 'yinv', 'ylabel',
'zmax', 'zmin', 'zrange', 'zinv', 'zlabel',
'cbmin', 'cbmax', 'cbrange'))
knownCurveOptions = frozenset(('legend', 'y2', 'with', 'tuplesize'))
knownInteractiveTerminals = frozenset(('x11', 'wxt', 'qt', 'aquaterm'))
# when testing plots with ASCII i/o, this is the unit of test data
testdataunit_ascii = 10
def _runSubprocess(cmd, input):
r'''Runs a given command feeding the given input to stdin. Waits for the command
to terminate, and returns the stdout,stderr tuple we get back
'''
process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate(input=b'%s' % input)
retcode = process.poll()
if retcode:
raise subprocess.CalledProcessError(retcode, cmd[0], output=out + err)
return out,err
def _getGnuplotFeatures():
# Be careful talking to gnuplot here. If you use a tty then gnuplot
# messes with the tty settings where it should NOT. For example it turns
# on the local echo. So make sure to not use a tty
# first, I run 'gnuplot --help' to extract all the cmdline options as features
helpstring = subprocess.check_output(['gnuplot', '--help'], stderr=subprocess.STDOUT)
features = set( re.findall(b'--([a-zA-Z0-9_]+)', helpstring ) )
# then I try to set a square aspect ratio for 3D to see if it works
out,err = _runSubprocess(['gnuplot'],
"""set view equal
exit
""")
# no output if works; some output if error
if( not ( out or err ) ):
features.add('equal_3d')
return frozenset(features)
features = _getGnuplotFeatures()
def _dictDeUnderscore(d):
r'''Takes a dict, and renames all keys that start with an '_' to not contain that
anymore. This is done because some keys are illegal as kwargs (notably
'with' and '3d'), so the user passes in '_with' and '_3d', which ARE legal
'''
d2 = {}
for key in d:
if isinstance(key, (str, bytes)) and key[0] == '_':
d2[key[1:]] = d[key]
else:
d2[key] = d[key]
return d2
class GnuplotlibError(Exception):
def __init__(self, err): self.err = err
def __str__(self): return self.err
class gnuplotlib:
def __init__(self, **plotOptions):
# some defaults
self.plotOptions = _dictDeUnderscore(plotOptions)
self.t0 = time.time()
self.checkpoint_stuck = False
self.sync_count = 1
plotOptionsCmds = self._getPlotOptionsCmds()
# if we already have a gnuplot process, reset it. Otherwise make a new
# one
if hasattr(self, 'gnuplotProcess') and self.gnuplotProcess:
self._printGnuplotPipe( "reset\nset output\n" )
self._checkpoint()
else:
self.gnuplotProcess = None
self._startgnuplot()
self._logEvent("_startgnuplot() finished")
self._safelyWriteToPipe(plotOptionsCmds)
def _startgnuplot(self):
self._logEvent("_startgnuplot()")
if not self.plotOptions.get('dump'):
cmd = ['gnuplot']
if 'persist' in features:
cmd += ['--persist']
self.fdDupSTDOUT = os.dup(sys.stdout.fileno())
self.gnuplotProcess = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# save the default terminal
self._safelyWriteToPipe("set terminal push", 'terminal')
def _getPlotOptionsCmds(self):
for option in self.plotOptions:
if not option in knownPlotOptions:
raise GnuplotlibError(option + ' is not a valid plot option')
# set some defaults
# plot with lines and points by default
if not 'with' in self.plotOptions:
self.plotOptions['with'] = 'linespoints'
# make sure I'm not passed invalid combinations of options
if self.plotOptions.get('3d'):
if 'y2min' in self.plotOptions or 'y2max' in self.plotOptions:
raise GnuplotlibError("'3d' does not make sense with 'y2'...")
if not 'equal_3d' in features and \
( self.plotOptions.get('square_xy') or self.plotOptions.get('square') ):
sys.stderr.write("Your gnuplot doesn't support square aspect ratios for 3D plots, so I'm ignoring that\n")
del self.plotOptions['square_xy']
del self.plotOptions['square']
else:
if self.plotOptions.get('square_xy'):
raise GnuplotlibError("'square_xy' only makes sense with '3d'")
# grid on by default
cmds = ['set grid']
# send all set/unset as is
for setunset in ('set', 'unset'):
if setunset in self.plotOptions:
if isinstance(self.plotOptions[setunset], (list, tuple)):
cmds += [ setunset + ' ' + setting for setting in self.plotOptions[setunset] ]
else:
cmds.append(setunset + ' ' + self.plotOptions[setunset])
# set the plot bounds
for axis in ('x', 'y', 'y2', 'z', 'cb'):
# if we have min AND max AND inv, I make sure that min>max, and
# suppress the inv. This is because in gnuplot 'plot [min:max]
# reverse' ingores the 'reverse' if both min and max are given
if axis + 'min' in self.plotOptions and \
axis + 'max' in self.plotOptions and \
self.plotOptions.get(axis + 'inv'):
minval = min(self.plotOptions[axis + 'min'], self.plotOptions[axis + 'max'])
maxval = max(self.plotOptions[axis + 'min'], self.plotOptions[axis + 'max'])
self.plotOptions[axis + 'min'] = maxval
self.plotOptions[axis + 'max'] = minval
self.plotOptions[axis + 'inv'] = False
# If a bound isn't given I want to set it to the empty string, so I can communicate it simply
# to gnuplot
rangeopt_name = axis + 'range'
for minmax in ('min', 'max'):
opt = axis + minmax
if not opt in self.plotOptions:
self.plotOptions[opt] = ''
else:
if rangeopt_name in self.plotOptions:
raise GnuplotlibError("Both {} and {} not allowed at the same time".format(opt,rangeopt_name))
self.plotOptions[opt] = str(self.plotOptions[opt])
# if any of the ranges are given, set the range
if len(self.plotOptions[axis + 'min'] + self.plotOptions[axis + 'max']):
rangeopt_val = ':'.join((self.plotOptions[axis + 'min'], self.plotOptions[axis + 'max']))
elif rangeopt_name in self.plotOptions:
# A range was given. If it's a string, just take it. It can also
# be a two-value list for the min/max
rangeopt_val = self.plotOptions[rangeopt_name]
if isinstance(rangeopt_val, (list, tuple)):
rangeopt_val = ':'.join(str(x) for x in rangeopt_val)
else:
rangeopt_val = ''
cmds.append( "set {} [{}] {}".format(rangeopt_name,
rangeopt_val,
'reverse' if self.plotOptions.get(axis + 'inv') else ''))
# set the curve labels
if not axis == 'cb':
if axis + 'label' in self.plotOptions:
cmds.append('set {axis}label "{label}"'.format(axis = axis,
label = self.plotOptions[axis + 'label']))
# set the title
if 'title' in self.plotOptions:
cmds.append('set title "' + self.plotOptions['title'] + '"')
# handle a requested square aspect ratio
# set a square aspect ratio. Gnuplot does this differently for 2D and 3D plots
if self.plotOptions.get('3d'):
if self.plotOptions.get('square'):
cmds.append("set view equal xyz")
elif self.plotOptions.get('square_xy'):
cmds.append("set view equal xy")
else:
if self.plotOptions.get('square'):
cmds.append("set size ratio -1")
# handle 'hardcopy'. This simply ties in to 'output' and 'terminal', handled
# later
if 'hardcopy' in self.plotOptions:
# 'hardcopy' is simply a shorthand for 'terminal' and 'output', so they
# can't exist together
if 'terminal' in self.plotOptions or 'output' in self.plotOptions:
raise GnuplotlibError(
"""The 'hardcopy' option can't coexist with either 'terminal' or 'output'. If the
defaults are acceptable, use 'hardcopy' only, otherwise use 'terminal' and
'output' to get more control""")
outputfile = self.plotOptions['hardcopy']
m = re.search(r'\.(eps|ps|pdf|png|svg)$', outputfile)
if not m:
raise GnuplotlibError("Only .eps, .ps, .pdf, .png and .svg hardcopy output supported")
outputfileType = m.group(1)
terminalOpts = { 'eps': 'postscript solid color enhanced eps',
'ps': 'postscript solid color landscape 10',
'pdf': 'pdf solid color font ",10" size 11in,8.5in',
'png': 'png size 1280,1024',
'svg': 'svg enhanced solid'}
self.plotOptions['terminal'] = terminalOpts[outputfileType]
self.plotOptions['output'] = outputfile
if 'terminal' in self.plotOptions:
if self.plotOptions['terminal'] in knownInteractiveTerminals:
# known interactive terminal
if 'output' in self.plotOptions and self.plotOptions['output'] != '':
sys.stderr.write("Warning: requested a known-interactive gnuplot terminal AND an output file. Is this REALLY what you want?\n")
# add the extra global options
if 'cmds' in self.plotOptions:
# if there's a single cmds option, put it into a 1-element list to
# make the processing work
if isinstance(self.plotOptions['cmds'], (list, tuple)):
cmds += self.plotOptions['cmds']
else:
cmds.append(self.plotOptions['cmds'])
return cmds
def __del__(self):
if self.gnuplotProcess:
if self.checkpoint_stuck:
self.gnuplotProcess.terminate()
else:
self._printGnuplotPipe( "exit\n" )
self.gnuplotProcess.wait()
self.gnuplotProcess = None
os.close(self.fdDupSTDOUT)
def _safelyWriteToPipe(self, input, flags=''):
def barfOnDisallowedCommands(line):
# I use STDERR as the backchannel, so I don't allow any "set print"
# commands, since those can disable that
if re.match(r'''(?: .*;)? # optionally wait for a semicolon
\s*
set\s+print\b''',
line, re.X):
raise GnuplotlibError("Please don't 'set print' since I use gnuplot's STDERR for error detection")
if re.match(r'''(?: .*;)? # optionally wait for a semicolon
\s*
print\b''',
line, re.X):
raise GnuplotlibError("Please don't ask gnuplot to 'print' anything since this can confuse my error detection")