gnuplot-snippets 0.1.5__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gnuplot_snippets/__init__.py +21 -0
- gnuplot_snippets/_utils.py +157 -0
- gnuplot_snippets/controller.py +484 -0
- gnuplot_snippets/demo.py +362 -0
- gnuplot_snippets/errors.py +13 -0
- gnuplot_snippets/snippets.py +519 -0
- gnuplot_snippets-0.1.5.dist-info/METADATA +222 -0
- gnuplot_snippets-0.1.5.dist-info/RECORD +11 -0
- gnuplot_snippets-0.1.5.dist-info/WHEEL +4 -0
- gnuplot_snippets-0.1.5.dist-info/entry_points.txt +3 -0
- gnuplot_snippets-0.1.5.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,519 @@
|
|
|
1
|
+
# Copyright (c) 2025-2026 Neil Temperley
|
|
2
|
+
# SPDX-License-Identifier: MIT
|
|
3
|
+
# See the LICENSE file in the project root for full license text.
|
|
4
|
+
# https://github.com/neiltemperley/gnuplot-snippets
|
|
5
|
+
"""Flexible unrestricted tools for Gnuplot integration with Python."""
|
|
6
|
+
import logging
|
|
7
|
+
|
|
8
|
+
import pandas as pd
|
|
9
|
+
|
|
10
|
+
logger = logging.getLogger("gnuplot_snippets")
|
|
11
|
+
from ._utils import (_check_cmd, _clean_cmds, _extract_set_terminal_cmd,
|
|
12
|
+
_flatten_to_tuple_of_strings, _source)
|
|
13
|
+
from .errors import GnuplotError
|
|
14
|
+
|
|
15
|
+
_gnuplot_datablock_counter: int = 0 # used to ensure unique datablock names.
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def next_datablock_counter() -> int:
|
|
19
|
+
"""Get and increment global counter to ensure unique Gnuplot datablock names.
|
|
20
|
+
Very useful to add to your code."""
|
|
21
|
+
global _gnuplot_datablock_counter
|
|
22
|
+
_gnuplot_datablock_counter += 1
|
|
23
|
+
return _gnuplot_datablock_counter
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def escape_str(s: str) -> str:
|
|
27
|
+
"""Escape underscores for Gnuplot titles and labels in "enhanced" terminals.
|
|
28
|
+
|
|
29
|
+
When a terminal is "enhanced" underscores signify subscripts.
|
|
30
|
+
Useful for showing a filename with underscores correctly in a title or label.
|
|
31
|
+
:param s: gnuplot title
|
|
32
|
+
:returns: escaped string
|
|
33
|
+
"""
|
|
34
|
+
return s.replace('_', '\\\\_')
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def format_dataframe(dataframe: pd.DataFrame,
|
|
38
|
+
column_formats: dict[str, str] | None = None) -> str:
|
|
39
|
+
"""Convert a dataframe to neat readable columns also suitable for a Gnuplot datablock or datafile.
|
|
40
|
+
|
|
41
|
+
Useful for visual examination of data.
|
|
42
|
+
|
|
43
|
+
Note: This assumes the column names are shorter than, or equal to, the field widths provided in column_formats.
|
|
44
|
+
So increase the field widths if necessary.
|
|
45
|
+
|
|
46
|
+
Note: If no column_formats is provided numbers are formatted according to pandas with better but imperfect
|
|
47
|
+
alignment of columns to data; OR If the same format for all columns is acceptable, omit column_formats
|
|
48
|
+
and try the equivalent of "df = df.map("{:8.2f}".format)" before calling this method.
|
|
49
|
+
|
|
50
|
+
:param dataframe: pandas 2D dataframe, e.g. with columns: 'column1', 'column2' etc.
|
|
51
|
+
:param column_formats: dict of form {'column1':'fmt1', 'column2':'fmt2', ...} where 'column1' etc matches
|
|
52
|
+
dataframe column names exactly and 'fmt1' etc is of the python form,
|
|
53
|
+
e.g. '8.2f', '', '5d'.
|
|
54
|
+
:returns: formatted string.
|
|
55
|
+
"""
|
|
56
|
+
if dataframe.empty:
|
|
57
|
+
return ""
|
|
58
|
+
column_formats = column_formats or {}
|
|
59
|
+
formatted_df = dataframe.copy()
|
|
60
|
+
# Create map:
|
|
61
|
+
formatted_map = {}
|
|
62
|
+
for col, fmt in column_formats.items():
|
|
63
|
+
formatted_map[col] = ("{:" + fmt + "}").format
|
|
64
|
+
# formatted_map[col] = lambda x, format=fmt: f"{x:{format}}"
|
|
65
|
+
# Convert data to formatted strings:
|
|
66
|
+
for col in dataframe.columns:
|
|
67
|
+
if col in formatted_map: #... ignore unknown keys
|
|
68
|
+
formatted_df[col] = dataframe[col].map(formatted_map[col])
|
|
69
|
+
else:
|
|
70
|
+
formatted_df[col] = dataframe[col].map(
|
|
71
|
+
lambda x: f"{x:}") # default formats of pandas
|
|
72
|
+
# Format header row to align to columns:
|
|
73
|
+
header = ""
|
|
74
|
+
first_row = formatted_df.iloc[0]
|
|
75
|
+
for col, cell in first_row.items():
|
|
76
|
+
header += f"{col:>{len(cell)}}\t"
|
|
77
|
+
return header + "\n" + formatted_df.to_csv(
|
|
78
|
+
header=False, index=False, sep="\t")
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _gp_escape(s: str) -> str:
|
|
82
|
+
"""Escape a string for use inside a Gnuplot double-quoted string."""
|
|
83
|
+
return s.replace("\\", "\\\\").replace('"', '\\"')
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
class GnuplotSnippets():
|
|
87
|
+
"""Save gnuplot command snippets to later combine for plotting.
|
|
88
|
+
|
|
89
|
+
Helper class for constructing and managing Gnuplot command snippets for use
|
|
90
|
+
with a GnuplotController. Supports datablocks, datafiles, publishing to file or screen, multiplot
|
|
91
|
+
workflows, and custom terminal/output setup.
|
|
92
|
+
|
|
93
|
+
Example::
|
|
94
|
+
|
|
95
|
+
# Typical usage (see individual methods for details):
|
|
96
|
+
# Inside class MyClass:
|
|
97
|
+
def gnuplot(self):
|
|
98
|
+
gs = GnuplotSnippets()
|
|
99
|
+
# Define scaled axes for undistorted 2D plot
|
|
100
|
+
gs.preplot(
|
|
101
|
+
'# Set variables for axis scaling:',
|
|
102
|
+
'if (!exists("XMIN") || !exists("XRANGE")) { XMIN=0.0; XRANGE=1.0 }',
|
|
103
|
+
'if (!exists("YMIN") || !exists("YRANGE")) { YMIN=0.0; YRANGE=1.5 }',
|
|
104
|
+
'set xrange [XMIN:XMIN+XRANGE]; set yrange [YMIN:YMIN+YRANGE]',
|
|
105
|
+
'set size ratio YRANGE/XRANGE',
|
|
106
|
+
)
|
|
107
|
+
# Set terminal for export (e.g., LaTeX-compatible PDF)
|
|
108
|
+
gs.output_to_file(
|
|
109
|
+
'set terminal cairolatex color pdf size 5.0,5.0*0.7 lw 2.0',
|
|
110
|
+
'set xlabel "$x$ [-]"; set format x "$%G$"',
|
|
111
|
+
'set ylabel "$y$ [-]"; set format y "$%G$"',
|
|
112
|
+
filename='output_filename.tex',
|
|
113
|
+
)
|
|
114
|
+
return gs
|
|
115
|
+
|
|
116
|
+
Then elsewhere::
|
|
117
|
+
|
|
118
|
+
my_object = MyClass()
|
|
119
|
+
gs = my_object.gnuplot() # get the snippets
|
|
120
|
+
|
|
121
|
+
gc = GnuplotController()
|
|
122
|
+
gc.preplot(gs.preplot(), gs.output_to_file(),)
|
|
123
|
+
gc.plot(gs.plot_elements(), pause=0) # Export to file
|
|
124
|
+
gc.postplot(gs.postplot())
|
|
125
|
+
|
|
126
|
+
# Switch back to screen display
|
|
127
|
+
gc.preplot(gs.output_to_screen())
|
|
128
|
+
gc.plot(gs.plot_elements(), pause=-1)
|
|
129
|
+
gc.postplot(gs.postplot())
|
|
130
|
+
|
|
131
|
+
gc.close()
|
|
132
|
+
|
|
133
|
+
Notes:
|
|
134
|
+
- `gc.preplot(gs.output_to_file())` and `gc.preplot(gs.output_to_screen())` are ignored during
|
|
135
|
+
active multiplot sessions.
|
|
136
|
+
- Use `gs.preplot()` for functions and set commands.
|
|
137
|
+
- Use `gc.preplot(gs.output_to_screen())` to switch from file output back to interactive display.
|
|
138
|
+
"""
|
|
139
|
+
|
|
140
|
+
def __init__(self, comment: str = "", debug: bool = False) -> None:
|
|
141
|
+
"""Initialise all snippets to empty.
|
|
142
|
+
|
|
143
|
+
:param comment: Comment to write to the script.
|
|
144
|
+
Note: If its multiline each line must begin with Gnuplot comment char "# ".
|
|
145
|
+
:param debug: If True get Gnuplot to print some helpful output.
|
|
146
|
+
"""
|
|
147
|
+
# These are Gnuplot command snippets:
|
|
148
|
+
# Set and unset commands to process before plotting:
|
|
149
|
+
self.__preplot: str = f'# {comment}\n' if comment else ""
|
|
150
|
+
# Plot elements for the next plot command in a more convenient form for altering:
|
|
151
|
+
self.__plot_elements: tuple[str, ...] = ()
|
|
152
|
+
self.__postplot: str = "" # set and unset commands to process after plotting
|
|
153
|
+
self.__preplot_to_screen: str = "" # set terminal and related commands for screen
|
|
154
|
+
self.__preplot_to_file: str = "" # set terminal and related commands for publishing to a file
|
|
155
|
+
#
|
|
156
|
+
self.is_debug: bool = debug # do some extra printouts from Gnuplot
|
|
157
|
+
return
|
|
158
|
+
|
|
159
|
+
def __str__(self) -> str:
|
|
160
|
+
"""Create object string for printing/debugging."""
|
|
161
|
+
s: str = ''
|
|
162
|
+
s += '### preplot to file \t=\n{}\n'.format(self.__preplot_to_file)
|
|
163
|
+
s += '### preplot to screen \t=\n{}\n'.format(self.__preplot_to_screen)
|
|
164
|
+
s += '### preplot \t=\n{}\n'.format(self.__preplot)
|
|
165
|
+
s += '### plot_elements \t=\n{}\n'.format(self.__plot_elements)
|
|
166
|
+
s += '### postplot \t=\n{}\n'.format(self.__postplot)
|
|
167
|
+
# s += ' = """{}"""\n'.format()
|
|
168
|
+
return s
|
|
169
|
+
|
|
170
|
+
def output_to_file(self,
|
|
171
|
+
*set_cmds: str,
|
|
172
|
+
filename: str | None = None,
|
|
173
|
+
show_source: bool = True) -> str:
|
|
174
|
+
"""Record gnuplot commands that direct plot output to a file.
|
|
175
|
+
|
|
176
|
+
Stores the given commands (usually a ``set terminal ...`` plus any
|
|
177
|
+
related publishing-specific settings such as labels and axis formats) and
|
|
178
|
+
returns the stored snippet.
|
|
179
|
+
|
|
180
|
+
Called with no arguments, it just returns the commands stored so far.
|
|
181
|
+
|
|
182
|
+
Usually the appropriate "set terminal ....", should be in set_cmds.
|
|
183
|
+
|
|
184
|
+
Example::
|
|
185
|
+
|
|
186
|
+
# Publishing in LaTeX:
|
|
187
|
+
gs = GnuplotSnippets()
|
|
188
|
+
gs.output_to_file(
|
|
189
|
+
'set terminal cairolatex color pdf size 5.0,5.0*0.7 lw 2.0',
|
|
190
|
+
'set title', # clear title
|
|
191
|
+
'set xlabel "$x$ [-]"; set format x "$%G$"',
|
|
192
|
+
'set ylabel "$y$ [-]"; set format y "$%G$"',
|
|
193
|
+
filename='output_filename.tex')
|
|
194
|
+
gs.plot_elements('cos(x)', 'sin(x)')
|
|
195
|
+
# Later do this...
|
|
196
|
+
gc = GnuplotController()
|
|
197
|
+
gc.preplot(gs.output_to_file(), gs.preplot())
|
|
198
|
+
gc.plot(gs.plot_elements()) # write plot to file
|
|
199
|
+
# gc.postplot(gs.postplot()) # clean up
|
|
200
|
+
gc.preplot(gs.output_to_screen())
|
|
201
|
+
gc.plot(gs.plot_elements(), pause=-1) # plot to screen
|
|
202
|
+
gc.close()
|
|
203
|
+
|
|
204
|
+
:param set_cmds: gnuplot commands, one per argument. Each may contain
|
|
205
|
+
several commands separated by newlines or semicolons.
|
|
206
|
+
Normally includes the appropriate ``set terminal ...``.
|
|
207
|
+
:param filename: Output file name.
|
|
208
|
+
:param show_source: If True, prepend a comment with caller of this method's details.
|
|
209
|
+
:returns: Preplot command string to direct output to file.
|
|
210
|
+
"""
|
|
211
|
+
if not set_cmds:
|
|
212
|
+
return self.__preplot_to_file
|
|
213
|
+
|
|
214
|
+
set_terminal_cmd, cmds = _extract_set_terminal_cmd(*set_cmds)
|
|
215
|
+
if set_terminal_cmd is None or filename is None:
|
|
216
|
+
raise ValueError(
|
|
217
|
+
"Both a 'set terminal ...' command and 'filename' "
|
|
218
|
+
"must be provided when giving commands.")
|
|
219
|
+
if set_terminal_cmd is not None:
|
|
220
|
+
_check_cmd(set_terminal_cmd) # simple validity check.
|
|
221
|
+
|
|
222
|
+
debug_output = ""
|
|
223
|
+
if self.is_debug and filename and set_terminal_cmd:
|
|
224
|
+
escaped_filename = filename.replace('"', '\\"')
|
|
225
|
+
escaped_cmd = set_terminal_cmd.replace('"', '\\"')
|
|
226
|
+
debug_output = f' print("GnuplotSnippets DEBUG: Setting output to: {escaped_filename}")\n print("GnuplotSnippets DEBUG: {escaped_cmd}")\n'
|
|
227
|
+
if set_terminal_cmd and filename:
|
|
228
|
+
snippet_source = f'# {_source()}\n' if show_source else ""
|
|
229
|
+
extra_cmds = _clean_cmds(*cmds) if cmds else ""
|
|
230
|
+
# Multiplot doesn't want to see any new terminal definitions
|
|
231
|
+
self.__preplot_to_file = (
|
|
232
|
+
snippet_source +
|
|
233
|
+
f'if(!GPVAL_MULTIPLOT) {{\n set output "{_gp_escape(filename)}"\n {set_terminal_cmd}\n{debug_output}}}\n{extra_cmds}'
|
|
234
|
+
)
|
|
235
|
+
return self.__preplot_to_file
|
|
236
|
+
|
|
237
|
+
def output_to_screen(self,
|
|
238
|
+
*set_cmds: str,
|
|
239
|
+
show_source: bool = True) -> str:
|
|
240
|
+
"""Replace the output_to_screen snippet with ``set_cmds``.
|
|
241
|
+
Usually contains 'set terminal ...' and related commands for screen output.
|
|
242
|
+
|
|
243
|
+
This will also clear the output with "set output".
|
|
244
|
+
|
|
245
|
+
Example::
|
|
246
|
+
|
|
247
|
+
gs = GnuplotSnippets()
|
|
248
|
+
gs.output_to_screen("set terminal qt size 800,800", show_source=True)
|
|
249
|
+
gs.plot_elements('cos(x)', 'sin(x)')
|
|
250
|
+
# Later do this...
|
|
251
|
+
gc = GnuplotController()
|
|
252
|
+
gc.preplot(gs.output_to_screen(), gs.preplot()) # explicitly direct output to screen
|
|
253
|
+
gc.plot(gs.plot_elements(), pause=-1)
|
|
254
|
+
gc.close()
|
|
255
|
+
|
|
256
|
+
You can ignore using this method if you are happy with the system screen default.
|
|
257
|
+
:param set_cmds: "set terminal ...", then any additional Gnuplot command lines specific to screen view.
|
|
258
|
+
:param show_source: If True, prepend a comment with caller of this method's details.
|
|
259
|
+
:returns: preplot snippet string to direct output to screen.
|
|
260
|
+
"""
|
|
261
|
+
if not set_cmds:
|
|
262
|
+
return self.__preplot_to_screen
|
|
263
|
+
set_terminal_cmd, cmds = _extract_set_terminal_cmd(*set_cmds)
|
|
264
|
+
if (set_terminal_cmd is None):
|
|
265
|
+
raise ValueError(
|
|
266
|
+
"Must have a 'set terminal ' command, e.g. 'set terminal qt'.")
|
|
267
|
+
else:
|
|
268
|
+
_check_cmd(set_terminal_cmd) # simple validity check.
|
|
269
|
+
|
|
270
|
+
debug_output = ""
|
|
271
|
+
if self.is_debug: # and set_terminal_cmd:
|
|
272
|
+
escaped_cmd = set_terminal_cmd.replace('"', '\\"')
|
|
273
|
+
debug_output = f' print("GnuplotSnippets DEBUG: Setting output to screen.")\n print("GnuplotSnippets DEBUG: {escaped_cmd}")\n'
|
|
274
|
+
snippet_source = f'# {_source()}\n' if show_source else ""
|
|
275
|
+
extra_cmds = _clean_cmds(*cmds) if cmds else ""
|
|
276
|
+
# Multiplot doesn't want to see any new terminal definitions
|
|
277
|
+
self.__preplot_to_screen = snippet_source + f'if(!GPVAL_MULTIPLOT) {{\n set output\n {set_terminal_cmd}\n{debug_output}}}\n{extra_cmds}'
|
|
278
|
+
return self.__preplot_to_screen
|
|
279
|
+
|
|
280
|
+
def preplot(self,
|
|
281
|
+
*set_cmds,
|
|
282
|
+
reset: bool = False,
|
|
283
|
+
show_source: bool = True) -> str:
|
|
284
|
+
"""Append one or more lines to the preplot snippet to be sent to gnuplot before plotting.
|
|
285
|
+
|
|
286
|
+
For example, all gnuplot "set" and "unset" commands: title, ranges, labels, arrows etc.
|
|
287
|
+
To set terminal use output_to_screen() or output_to_file().
|
|
288
|
+
See also preplot_add_datablock().
|
|
289
|
+
:param set_cmds: one or more set/unset commands.
|
|
290
|
+
:param reset: if True clear preplot snippet before appending. Usually not required.
|
|
291
|
+
:param show_source: when True prepend a comment indicating caller details of this method.
|
|
292
|
+
:returns: preplot snippet string.
|
|
293
|
+
"""
|
|
294
|
+
snippet_source = f'# {_source()}\n' if set_cmds and show_source else ""
|
|
295
|
+
if reset:
|
|
296
|
+
self.__preplot = "" # clear
|
|
297
|
+
self.__preplot += snippet_source + _clean_cmds(*set_cmds)
|
|
298
|
+
return self.__preplot
|
|
299
|
+
|
|
300
|
+
def preplot_add_datablock(self,
|
|
301
|
+
dataframe: pd.DataFrame,
|
|
302
|
+
datablock_name: str = "$DataBlock1",
|
|
303
|
+
column_formats: dict[str, str] | None = None,
|
|
304
|
+
show_source: bool = True) -> str:
|
|
305
|
+
"""Convert a pandas dataframe to a gnuplot datablock and append it to the preplot snippet.
|
|
306
|
+
The dataframe should include column headers.
|
|
307
|
+
|
|
308
|
+
For more sophisticated plots, e.g. with contours, use preplot_add_datafile().
|
|
309
|
+
|
|
310
|
+
Example::
|
|
311
|
+
|
|
312
|
+
df = pd.DataFrame(points, columns=['x_m', 'y_m'])
|
|
313
|
+
datablock_name = f'$DataBlock_Profile{next_datablock_counter()}'
|
|
314
|
+
gs = GnuplotSnippets()
|
|
315
|
+
gs.preplot_add_datablock(df, datablock_name=datablock_name)
|
|
316
|
+
gs.plot_elements('{db} using "x_m":"y_m" {title} with linepoints linetype {lt} linewidth {lw}'.format(
|
|
317
|
+
db=datablock_name,
|
|
318
|
+
title=f'title "{self.name}"',
|
|
319
|
+
lt=self.style.get('linetype', 1),
|
|
320
|
+
lw=self.style.get('linewidth', 1.5),
|
|
321
|
+
))
|
|
322
|
+
gc.preplot(gs.preplot())
|
|
323
|
+
gc.plot(gs.plot_elements(), pause=-1)
|
|
324
|
+
gc.postplot(gs.postplot())
|
|
325
|
+
gc.close()
|
|
326
|
+
|
|
327
|
+
Note:
|
|
328
|
+
"set datafile columnheaders" # is sent to gnuplot by this method.
|
|
329
|
+
:param dataframe: pandas DataFrame with column headers.
|
|
330
|
+
:param datablock_name: str unique valid gnuplot datablock name. Default is "$DataBlock1". Use this same name
|
|
331
|
+
when creating the plot_elements()!
|
|
332
|
+
:param column_formats: used to optionally format the block to be more human readable.
|
|
333
|
+
:param show_source: when True prepend a comment indicating caller details of this method.
|
|
334
|
+
|
|
335
|
+
:returns: preplot snippet
|
|
336
|
+
"""
|
|
337
|
+
snippet_source = f'# {_source()}\n' if show_source else ""
|
|
338
|
+
separator = "\t" # data separator
|
|
339
|
+
self.__preplot += snippet_source + f'set datafile separator "{separator}"\nset datafile columnheaders\n'
|
|
340
|
+
content = format_dataframe(dataframe, column_formats=column_formats)
|
|
341
|
+
self.__preplot += f'{datablock_name} << EOD\n{content}EOD\n' # Note: could add '#' before {content} to comment out the column header but not required.
|
|
342
|
+
return self.__preplot
|
|
343
|
+
|
|
344
|
+
def preplot_add_datafile(self,
|
|
345
|
+
datasets: list[pd.DataFrame],
|
|
346
|
+
datafile: str = "",
|
|
347
|
+
column_formats: dict[str, str] | None = None,
|
|
348
|
+
show_source: bool = True) -> str:
|
|
349
|
+
"""Create a single or "multi-data-set" Gnuplot datafile from a list
|
|
350
|
+
of DataFrames.
|
|
351
|
+
|
|
352
|
+
The dataframe(s) should include column headers.
|
|
353
|
+
|
|
354
|
+
Example::
|
|
355
|
+
|
|
356
|
+
gs = GnuplotSnippets()
|
|
357
|
+
gs.preplot('array Set_IDs[3] = ["1st", "2nd", "3rd"]') # we use this gnuplot array when plotting.
|
|
358
|
+
gs.preplot_add_datafile(dfs, datafile=datafile) # dfs = list[np.dataframe] one per dataset.
|
|
359
|
+
gs.plot_elements(f'for [i=1:|Set_IDs|] "{datafile}" index i-1 using 1:2 title sprintf("Contour = %s", Set_IDs[i]) with lines')
|
|
360
|
+
OR::
|
|
361
|
+
gs.plot_elements(f'for [i=1:{len(dfs)}] "{datafile}" index i-1 using 2:3 notitle with lines')
|
|
362
|
+
# Then later:
|
|
363
|
+
gc = GnuplotController()
|
|
364
|
+
gc.preplot(gs.preplot())
|
|
365
|
+
gc.plot(gs.plot_elements(), pause=-1)
|
|
366
|
+
gc.close()
|
|
367
|
+
#
|
|
368
|
+
Note:
|
|
369
|
+
set datafile columnheaders # is sent to Gnuplot by this method.
|
|
370
|
+
:param datasets: list of pandas DataFrames where each DataFrame is a gnuplot dataset. Each DataFrame should have column headers.
|
|
371
|
+
:param datafile: This will create this Gnuplot-compatible multi-dataset datafile.
|
|
372
|
+
:param column_formats: used to optionally format the datafile to be more human readable.
|
|
373
|
+
Dict of form {'column1':'fmt1', 'column2':'fmt2', ...} where 'column1' etc matches dataframe
|
|
374
|
+
column names exactly and 'fmt1' etc is of the python form,
|
|
375
|
+
e.g. '8.2f', '', '5d'.
|
|
376
|
+
:param show_source: when True prepend a comment indicating caller details of this method.
|
|
377
|
+
:returns: preplot snippet
|
|
378
|
+
"""
|
|
379
|
+
if not datasets:
|
|
380
|
+
raise GnuplotError("datasets cannot be empty!")
|
|
381
|
+
if not datafile or "\n" in datafile:
|
|
382
|
+
raise GnuplotError(f"Invalid datafile name: {datafile!r}")
|
|
383
|
+
column_formats = column_formats or {}
|
|
384
|
+
snippet_source = f"# {_source()}\n" if show_source else ""
|
|
385
|
+
blocks = [
|
|
386
|
+
format_dataframe(df, column_formats=column_formats)
|
|
387
|
+
for df in datasets
|
|
388
|
+
]
|
|
389
|
+
with open(datafile, "w", encoding="utf-8") as f:
|
|
390
|
+
f.write("\n\n".join(blocks))
|
|
391
|
+
separator = "\t" # data separator
|
|
392
|
+
self.__preplot += (snippet_source +
|
|
393
|
+
f'set datafile separator "{separator}"\n'
|
|
394
|
+
'set datafile columnheaders\n')
|
|
395
|
+
if self.is_debug:
|
|
396
|
+
escaped_filename = datafile.replace("\\",
|
|
397
|
+
"\\\\").replace('"', '\\"')
|
|
398
|
+
self.__preplot += (
|
|
399
|
+
f'print("GnuplotSnippets DEBUG: Python wrote multi-dataset datafile {escaped_filename}")\n'
|
|
400
|
+
f'print("GnuplotSnippets DEBUG: Usage example: plot \\"{escaped_filename}\\" '
|
|
401
|
+
f'for [i=1:3] index i-1 using 1:2 title sprintf(\\"Contour: %d\\", i)")\n'
|
|
402
|
+
)
|
|
403
|
+
return self.__preplot
|
|
404
|
+
|
|
405
|
+
def plot_elements(
|
|
406
|
+
self,
|
|
407
|
+
*plot_elements: str | tuple[str, ...],
|
|
408
|
+
reset: bool = False,
|
|
409
|
+
) -> tuple[str, ...]:
|
|
410
|
+
"""Append one or more Gnuplot "plot element" lines to the plot elements snippet.
|
|
411
|
+
|
|
412
|
+
Recall (from Gnuplot help), that a plot command for Gnuplot looks like this:
|
|
413
|
+
plot {<ranges>} <plot-element1> {, <plot-element2>, <plot-element3>}
|
|
414
|
+
This method accepts either:
|
|
415
|
+
- Multiple element strings as arguments: plot_elements(plot_element1, plot_element2)
|
|
416
|
+
- Tuples of plot element strings: plot_elements((plot_element1, plot_element2))
|
|
417
|
+
|
|
418
|
+
Example::
|
|
419
|
+
gs = GnuplotSnippets()
|
|
420
|
+
gs.plot_elements('cos(x)', 'sin(x) title "Sin Demo" linewidth 2.0')
|
|
421
|
+
gc = GnuplotController()
|
|
422
|
+
gc.preplot(gs.preplot())
|
|
423
|
+
gc.plot(gs.plot_elements(), pause=-1) # send plot element snippets to controller and plot
|
|
424
|
+
gc.postplot(gs.postplot())
|
|
425
|
+
gc.close()
|
|
426
|
+
:param plot_elements: one or more Gnuplot plot elements, e.g. "sin(x)"
|
|
427
|
+
:param reset: if true clear plot elements before appending.
|
|
428
|
+
:returns: tuple of plot_elements
|
|
429
|
+
"""
|
|
430
|
+
if reset:
|
|
431
|
+
self.__plot_elements = () # clear
|
|
432
|
+
# Replace with a new extended tuple:
|
|
433
|
+
self.__plot_elements += _flatten_to_tuple_of_strings(plot_elements)
|
|
434
|
+
return self.__plot_elements
|
|
435
|
+
|
|
436
|
+
def postplot(self,
|
|
437
|
+
*post_plot_cmds,
|
|
438
|
+
defaults: bool = False,
|
|
439
|
+
reset: bool = False,
|
|
440
|
+
show_source: bool = True) -> str:
|
|
441
|
+
"""Append one or more post_plot_cmds to the postplot snippet to be sent to gnuplot after plotting.
|
|
442
|
+
|
|
443
|
+
Usually "unset" commands, e.g. unset label; unset arrow; etc.
|
|
444
|
+
Note: "unset multiplot" is not required in this snippet; it is done automatically by
|
|
445
|
+
GnuplotController.postmultiplot().
|
|
446
|
+
|
|
447
|
+
Examples to consider: "unset format x; unset xdata; unset x2tics; unset x2mtics; unset y2mtics;"
|
|
448
|
+
Only required if you want to follow up with another graph without reseting.
|
|
449
|
+
|
|
450
|
+
Example::
|
|
451
|
+
|
|
452
|
+
gs1 = GnuplotSnippets()
|
|
453
|
+
gs1.plot_elements('cos(x)', 'sin(x)')
|
|
454
|
+
gs2 = GnuplotSnippets()
|
|
455
|
+
gs2.plot_elements('tan(x)')
|
|
456
|
+
#
|
|
457
|
+
gc = GnuplotController()
|
|
458
|
+
gc.preplot(gs1.preplot())
|
|
459
|
+
gc.plot(gs1.plot_elements(), pause=-1)
|
|
460
|
+
gc.postplot(gs1.postplot()) # tidy up before the next plot.
|
|
461
|
+
gc.plot(gs2.plot_elements(), pause=-1)
|
|
462
|
+
gc.close()
|
|
463
|
+
|
|
464
|
+
:param post_plot_cmds: one or more commands to send after plotting.
|
|
465
|
+
:param defaults: = True to use fairly safe typical commands.
|
|
466
|
+
:param reset: if true clear postplot snippet before appending. Usually not required.
|
|
467
|
+
:param show_source: bool when True prepend a comment indicating caller details of this method.
|
|
468
|
+
:returns: post plot command string
|
|
469
|
+
"""
|
|
470
|
+
snippet_source = f'# {_source()}\n' if (
|
|
471
|
+
post_plot_cmds or defaults) and show_source else ""
|
|
472
|
+
if reset:
|
|
473
|
+
self.__postplot = "" # clear
|
|
474
|
+
default_cmds = ""
|
|
475
|
+
if defaults:
|
|
476
|
+
default_cmds = 'unset label; unset arrow; set output\n'
|
|
477
|
+
self.__postplot += snippet_source + default_cmds + _clean_cmds(
|
|
478
|
+
*post_plot_cmds)
|
|
479
|
+
return self.__postplot
|
|
480
|
+
|
|
481
|
+
def append(self, *snippets):
|
|
482
|
+
"""Append a list, tuple or single snippet onto self.
|
|
483
|
+
|
|
484
|
+
Handles append(snippet), append([s1, s2, ...]), append((s1, s2, ...))
|
|
485
|
+
or append(s1, s2, ...).
|
|
486
|
+
Useful when combining several GnuplotSnippets from different objects into one.
|
|
487
|
+
|
|
488
|
+
Example::
|
|
489
|
+
|
|
490
|
+
gs1 = GnuplotSnippets()
|
|
491
|
+
gs1.plot_elements('cos(x)', 'sin(x)')
|
|
492
|
+
gs2 = GnuplotSnippets()
|
|
493
|
+
gs2.plot_elements('tan(x)')
|
|
494
|
+
#
|
|
495
|
+
gs1.append(gs2) # Append gs2 so now all appear on the one plot.
|
|
496
|
+
gc = GnuplotController()
|
|
497
|
+
gc.preplot(gs1.preplot())
|
|
498
|
+
gc.plot(gs1.plot_elements(), pause=-1)
|
|
499
|
+
gc.close()
|
|
500
|
+
# EQUIVALENT TO:
|
|
501
|
+
gc.preplot(gs1.preplot(), gs2.preplot())
|
|
502
|
+
gc.plot(gs1.plot_elements(), gs2.plot_elements(), pause=-1)
|
|
503
|
+
"""
|
|
504
|
+
if len(snippets) == 1 and isinstance(snippets[0], (list, tuple)):
|
|
505
|
+
items = snippets[0] # a list or tuple of snippets was passed
|
|
506
|
+
else:
|
|
507
|
+
items = snippets # multiple arguments or a single snippet
|
|
508
|
+
for sn in items:
|
|
509
|
+
# Merge the already-cleaned snippets verbatim: re-running _clean_cmds
|
|
510
|
+
# would strip trailing tabs from datablock rows.
|
|
511
|
+
self.__preplot += sn.preplot()
|
|
512
|
+
self.plot_elements(sn.plot_elements())
|
|
513
|
+
self.__postplot += sn.postplot()
|
|
514
|
+
# Output snippets are replaced, not merged: the last one given wins.
|
|
515
|
+
if sn.output_to_file():
|
|
516
|
+
self.__preplot_to_file = sn.output_to_file()
|
|
517
|
+
if sn.output_to_screen():
|
|
518
|
+
self.__preplot_to_screen = sn.output_to_screen()
|
|
519
|
+
return self
|