gnuplot-snippets 0.1.5__tar.gz
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-0.1.5/LICENSE +21 -0
- gnuplot_snippets-0.1.5/PKG-INFO +222 -0
- gnuplot_snippets-0.1.5/README.md +202 -0
- gnuplot_snippets-0.1.5/pyproject.toml +40 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/__init__.py +21 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/_utils.py +157 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/controller.py +484 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/demo.py +362 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/errors.py +13 -0
- gnuplot_snippets-0.1.5/src/gnuplot_snippets/snippets.py +519 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Neil Temperley
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gnuplot-snippets
|
|
3
|
+
Version: 0.1.5
|
|
4
|
+
Summary: Composable gnuplot snippets for Python, for interactive and batch plotting by advanced users
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: Neil Temperley
|
|
8
|
+
Requires-Python: >=3.10
|
|
9
|
+
Classifier: Programming Language :: Python :: 3
|
|
10
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
15
|
+
Requires-Dist: pandas (>=2.2.3)
|
|
16
|
+
Project-URL: Licence, https://github.com/neiltemperley/gnuplot-snippets/blob/main/LICENSE
|
|
17
|
+
Project-URL: Repository, https://github.com/neiltemperley/gnuplot-snippets
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
|
|
20
|
+
# gnuplot-snippets
|
|
21
|
+
|
|
22
|
+
Composable gnuplot snippets for Python, for interactive and batch plotting by advanced users.
|
|
23
|
+
|
|
24
|
+
Tools for tightly integrating gnuplot with Python, enabling flexible
|
|
25
|
+
graph-by-graph interaction, interactive exploration, and batch
|
|
26
|
+
publishing — all from within Python.
|
|
27
|
+
|
|
28
|
+
Designed for gnuplot power users who need to visualize complex data
|
|
29
|
+
across different Python objects and classes with minimal gnuplot
|
|
30
|
+
rescripting per plot.
|
|
31
|
+
|
|
32
|
+
## Features
|
|
33
|
+
|
|
34
|
+
- Unrestricted access to gnuplot commands from Python.
|
|
35
|
+
- Minimal gnuplot code duplication across different plots.
|
|
36
|
+
- Gnuplot script logic resides primarily inside object classes.
|
|
37
|
+
- Native-feeling plot window interaction (as if running gnuplot directly).
|
|
38
|
+
- Interactive gradient and coordinate measurement via mouse.
|
|
39
|
+
- Batch-mode rendering for publication workflows.
|
|
40
|
+
- Logging and optional gnuplot stand-alone script dumping for debug and inspection.
|
|
41
|
+
- Python source markers in stand-alone scripts.
|
|
42
|
+
- Neat human-readable formatting of gnuplot datablocks and datafiles.
|
|
43
|
+
|
|
44
|
+
## Overview
|
|
45
|
+
|
|
46
|
+
Creating one-off plots from Python using existing gnuplot packages is
|
|
47
|
+
easy — but managing large, layered plots with data originating from
|
|
48
|
+
multiple classes is not. And Python packages often lack the same
|
|
49
|
+
interactive behavior that comes from launching a gnuplot session
|
|
50
|
+
directly.
|
|
51
|
+
|
|
52
|
+
Conversely, managing a large number of interactive and publication
|
|
53
|
+
plots solely using gnuplot script files results in large, complex files
|
|
54
|
+
that are difficult to navigate and manage.
|
|
55
|
+
|
|
56
|
+
This module addresses both issues by:
|
|
57
|
+
|
|
58
|
+
- Organizing reusable gnuplot script fragments.
|
|
59
|
+
- Re-enabling interactive plotting behaviors from Python.
|
|
60
|
+
- Introducing new interactive features (like mouse measurements).
|
|
61
|
+
- Enabling a "preview then publish" workflow across multiple plots.
|
|
62
|
+
|
|
63
|
+
The fundamental principle of snippets as implemented here is that each
|
|
64
|
+
object class should generate gnuplot scripts (snippets) to plot itself
|
|
65
|
+
on screen or to a file. To plot multiple objects on the same graph,
|
|
66
|
+
or to create a multiplot graph, those snippets are simply combined
|
|
67
|
+
with a minimum of additional gnuplot commands.
|
|
68
|
+
|
|
69
|
+
> **Note:** This package is *not intended for gnuplot beginners*. It assumes
|
|
70
|
+
> comfort with gnuplot syntax and behavior. It does *not* provide a
|
|
71
|
+
> simplified interface to gnuplot; rather, it gives experienced users
|
|
72
|
+
> unrestricted access to gnuplot from within Python.
|
|
73
|
+
|
|
74
|
+
## Background
|
|
75
|
+
|
|
76
|
+
I often work with multiple mathematical models, each represented by a
|
|
77
|
+
class with one or more `gnuplot_xxx()` methods. These models typically
|
|
78
|
+
generate gnuplot datablocks or multi-contour datafiles.
|
|
79
|
+
|
|
80
|
+
Things become complex when combining models, e.g. overlaying two
|
|
81
|
+
models with multiple axes, creating a multiplot, or using glorious
|
|
82
|
+
gnuplot constructs such as:
|
|
83
|
+
|
|
84
|
+
```text
|
|
85
|
+
plot \
|
|
86
|
+
for [i=1:nContoursModelA] "datafileModelA.dat" index i-1 using 1:(column("Performance_Gap")) axes x1y2 title sprintf("Model A, Contour=%d",aContoursModelA[i]) lw 2.5, \
|
|
87
|
+
for [i=1:nContoursModelB] "datafileModelB.dat" index i-1 using 1:(column("Performance_Gap")) axes x1y2 title sprintf("Model B, Contour=%d",aContoursModelB[i]) lw 2.5, \
|
|
88
|
+
$DataBlockModelC using 1:3 title "Model C" lw 2.5 dt 2
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
This module provides Python-side containers for such gnuplot snippets,
|
|
92
|
+
allowing you to mix and match them to create plots with minimal script
|
|
93
|
+
duplication.
|
|
94
|
+
|
|
95
|
+
During model research and development, I often:
|
|
96
|
+
|
|
97
|
+
- Display plots interactively, one at a time, and publish PDF or
|
|
98
|
+
LaTeX versions as I go.
|
|
99
|
+
- Later switch to batch mode to render PDF or LaTeX-ready plots for publication.
|
|
100
|
+
|
|
101
|
+
This toolset was built to support that workflow. It won't do
|
|
102
|
+
everything for you — but it removes a lot of friction.
|
|
103
|
+
|
|
104
|
+
## Requirements
|
|
105
|
+
|
|
106
|
+
- Python 3.10 or newer
|
|
107
|
+
- [gnuplot](http://www.gnuplot.info/) installed and available on your `PATH`
|
|
108
|
+
- Tested with gnuplot 5.4 (check with `gnuplot --version`) on Linux.
|
|
109
|
+
|
|
110
|
+
## Installation
|
|
111
|
+
|
|
112
|
+
```bash
|
|
113
|
+
pip install gnuplot-snippets
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
To try it in a throwaway environment first:
|
|
117
|
+
|
|
118
|
+
```bash
|
|
119
|
+
deactivate 2>/dev/null # exit any active environment
|
|
120
|
+
mkdir -p ~/tmp
|
|
121
|
+
cd ~/tmp
|
|
122
|
+
python3 -m venv ~/tmp/gp-snippets-test
|
|
123
|
+
source ~/tmp/gp-snippets-test/bin/activate
|
|
124
|
+
# On Windows: %USERPROFILE%\tmp\gp-snippets-test\Scripts\activate
|
|
125
|
+
python -m pip install --upgrade pip
|
|
126
|
+
pip install gnuplot-snippets
|
|
127
|
+
|
|
128
|
+
# Check it works:
|
|
129
|
+
pip show -f gnuplot-snippets
|
|
130
|
+
python -c "import gnuplot_snippets; print(gnuplot_snippets.__file__)"
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Then run the demo (see [Full demo](#full-demo) below).
|
|
134
|
+
|
|
135
|
+
## Quick example
|
|
136
|
+
|
|
137
|
+
Provide a class a `gnuplot()` method that returns a `GnuplotSnippets`:
|
|
138
|
+
|
|
139
|
+
```python
|
|
140
|
+
from gnuplot_snippets import GnuplotController, GnuplotSnippets
|
|
141
|
+
|
|
142
|
+
class Car:
|
|
143
|
+
|
|
144
|
+
def __init__(self, name, a, b, c):
|
|
145
|
+
self.name, self.a, self.b, self.c = name, a, b, c
|
|
146
|
+
|
|
147
|
+
def gnuplot(self) -> GnuplotSnippets:
|
|
148
|
+
gs = GnuplotSnippets()
|
|
149
|
+
gs.output_to_screen(
|
|
150
|
+
'set terminal qt title "Car Performance"',
|
|
151
|
+
'set xlabel "Time [s]"; set format x',
|
|
152
|
+
'set ylabel "Velocity [m/s]"; set format y "%0.1f"',
|
|
153
|
+
'set y2label "Acceleration [m/s^2]"; set format y2',
|
|
154
|
+
'set ytics nomirror; set y2tics',
|
|
155
|
+
show_source=True) # add source marker to script file
|
|
156
|
+
gs.preplot(
|
|
157
|
+
'fVelocity(t,a,b,c) = a*t**3 + b*t**2 + c*t',
|
|
158
|
+
'fAcceleration(t,a,b,c) = 3.*a*t**2 + 2.*b*t + c',
|
|
159
|
+
f'set title "Performance for {self.name}"',
|
|
160
|
+
show_source=True)
|
|
161
|
+
gs.plot_elements(
|
|
162
|
+
f'fVelocity(x,{self.a},{self.b},{self.c}) title "{self.name}" with lines',
|
|
163
|
+
f'fAcceleration(x,{self.a},{self.b},{self.c}) axis x1y2 title "{self.name} Acceleration" with lines',
|
|
164
|
+
)
|
|
165
|
+
gs.postplot('unset label')
|
|
166
|
+
return gs
|
|
167
|
+
|
|
168
|
+
gc = GnuplotController(script_filename="my_script.gp")
|
|
169
|
+
gs = Car("Car1", 0.01, 0.0001, 0.1).gnuplot()
|
|
170
|
+
|
|
171
|
+
# Note: Args to gc.preplot() are snippets or gnuplot commands.
|
|
172
|
+
# gs.preplot() returns the preplot() snippet string.
|
|
173
|
+
gc.preplot(gs.preplot(), "set xrange[0:15]", "set y2range[0:*]", gs.output_to_screen())
|
|
174
|
+
gc.plot(gs.plot_elements(), pause=4) # wait 4s
|
|
175
|
+
|
|
176
|
+
# Change title and repeat plot with interactive measurement:
|
|
177
|
+
gc.preplot(
|
|
178
|
+
'set title "Interactive Demo. \\nClick in this window, press \'m\' key, then click two points."'
|
|
179
|
+
)
|
|
180
|
+
gc.plot(gs.plot_elements(), pause="mouse_measure") # interactive
|
|
181
|
+
gc.postplot(gs.postplot())
|
|
182
|
+
gc.close()
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
### Notes
|
|
186
|
+
|
|
187
|
+
- The example above uses the `qt` terminal. On Windows, switch to the
|
|
188
|
+
`windows` terminal (see the comment in the demo).
|
|
189
|
+
- Commands are sent to gnuplot in the order you pass them, so later `set`
|
|
190
|
+
commands override earlier ones, just like a normal gnuplot script.
|
|
191
|
+
- Here every command is also written to `my_script.gp`, so you can re-run or
|
|
192
|
+
debug it directly with `gnuplot my_script.gp`.
|
|
193
|
+
|
|
194
|
+
## Full demo
|
|
195
|
+
|
|
196
|
+
The full demo covers plotting to the screen, publishing to a PDF, overlaying
|
|
197
|
+
two objects on one graph, and using the controller directly without snippets
|
|
198
|
+
(including the interactive `mouse_measure` pause). Use it as a template to
|
|
199
|
+
get started.
|
|
200
|
+
|
|
201
|
+
```bash
|
|
202
|
+
python -m gnuplot_snippets.demo
|
|
203
|
+
# OR:
|
|
204
|
+
gnuplot-snippets-demo
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
Demo source: https://github.com/neiltemperley/gnuplot-snippets/blob/main/src/gnuplot_snippets/demo.py
|
|
208
|
+
|
|
209
|
+
## Security
|
|
210
|
+
|
|
211
|
+
Snippets are passed to gnuplot verbatim, and gnuplot can run shell commands
|
|
212
|
+
(e.g. via `system`) and write files. Never build snippets from untrusted
|
|
213
|
+
input, and choose safe filenames for script and output files.
|
|
214
|
+
|
|
215
|
+
## License
|
|
216
|
+
|
|
217
|
+
Released under the [MIT License](https://github.com/neiltemperley/gnuplot-snippets/blob/main/LICENSE).
|
|
218
|
+
|
|
219
|
+
## Disclaimer
|
|
220
|
+
|
|
221
|
+
This is an unofficial project and is not affiliated with gnuplot.
|
|
222
|
+
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# gnuplot-snippets
|
|
2
|
+
|
|
3
|
+
Composable gnuplot snippets for Python, for interactive and batch plotting by advanced users.
|
|
4
|
+
|
|
5
|
+
Tools for tightly integrating gnuplot with Python, enabling flexible
|
|
6
|
+
graph-by-graph interaction, interactive exploration, and batch
|
|
7
|
+
publishing — all from within Python.
|
|
8
|
+
|
|
9
|
+
Designed for gnuplot power users who need to visualize complex data
|
|
10
|
+
across different Python objects and classes with minimal gnuplot
|
|
11
|
+
rescripting per plot.
|
|
12
|
+
|
|
13
|
+
## Features
|
|
14
|
+
|
|
15
|
+
- Unrestricted access to gnuplot commands from Python.
|
|
16
|
+
- Minimal gnuplot code duplication across different plots.
|
|
17
|
+
- Gnuplot script logic resides primarily inside object classes.
|
|
18
|
+
- Native-feeling plot window interaction (as if running gnuplot directly).
|
|
19
|
+
- Interactive gradient and coordinate measurement via mouse.
|
|
20
|
+
- Batch-mode rendering for publication workflows.
|
|
21
|
+
- Logging and optional gnuplot stand-alone script dumping for debug and inspection.
|
|
22
|
+
- Python source markers in stand-alone scripts.
|
|
23
|
+
- Neat human-readable formatting of gnuplot datablocks and datafiles.
|
|
24
|
+
|
|
25
|
+
## Overview
|
|
26
|
+
|
|
27
|
+
Creating one-off plots from Python using existing gnuplot packages is
|
|
28
|
+
easy — but managing large, layered plots with data originating from
|
|
29
|
+
multiple classes is not. And Python packages often lack the same
|
|
30
|
+
interactive behavior that comes from launching a gnuplot session
|
|
31
|
+
directly.
|
|
32
|
+
|
|
33
|
+
Conversely, managing a large number of interactive and publication
|
|
34
|
+
plots solely using gnuplot script files results in large, complex files
|
|
35
|
+
that are difficult to navigate and manage.
|
|
36
|
+
|
|
37
|
+
This module addresses both issues by:
|
|
38
|
+
|
|
39
|
+
- Organizing reusable gnuplot script fragments.
|
|
40
|
+
- Re-enabling interactive plotting behaviors from Python.
|
|
41
|
+
- Introducing new interactive features (like mouse measurements).
|
|
42
|
+
- Enabling a "preview then publish" workflow across multiple plots.
|
|
43
|
+
|
|
44
|
+
The fundamental principle of snippets as implemented here is that each
|
|
45
|
+
object class should generate gnuplot scripts (snippets) to plot itself
|
|
46
|
+
on screen or to a file. To plot multiple objects on the same graph,
|
|
47
|
+
or to create a multiplot graph, those snippets are simply combined
|
|
48
|
+
with a minimum of additional gnuplot commands.
|
|
49
|
+
|
|
50
|
+
> **Note:** This package is *not intended for gnuplot beginners*. It assumes
|
|
51
|
+
> comfort with gnuplot syntax and behavior. It does *not* provide a
|
|
52
|
+
> simplified interface to gnuplot; rather, it gives experienced users
|
|
53
|
+
> unrestricted access to gnuplot from within Python.
|
|
54
|
+
|
|
55
|
+
## Background
|
|
56
|
+
|
|
57
|
+
I often work with multiple mathematical models, each represented by a
|
|
58
|
+
class with one or more `gnuplot_xxx()` methods. These models typically
|
|
59
|
+
generate gnuplot datablocks or multi-contour datafiles.
|
|
60
|
+
|
|
61
|
+
Things become complex when combining models, e.g. overlaying two
|
|
62
|
+
models with multiple axes, creating a multiplot, or using glorious
|
|
63
|
+
gnuplot constructs such as:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
plot \
|
|
67
|
+
for [i=1:nContoursModelA] "datafileModelA.dat" index i-1 using 1:(column("Performance_Gap")) axes x1y2 title sprintf("Model A, Contour=%d",aContoursModelA[i]) lw 2.5, \
|
|
68
|
+
for [i=1:nContoursModelB] "datafileModelB.dat" index i-1 using 1:(column("Performance_Gap")) axes x1y2 title sprintf("Model B, Contour=%d",aContoursModelB[i]) lw 2.5, \
|
|
69
|
+
$DataBlockModelC using 1:3 title "Model C" lw 2.5 dt 2
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
This module provides Python-side containers for such gnuplot snippets,
|
|
73
|
+
allowing you to mix and match them to create plots with minimal script
|
|
74
|
+
duplication.
|
|
75
|
+
|
|
76
|
+
During model research and development, I often:
|
|
77
|
+
|
|
78
|
+
- Display plots interactively, one at a time, and publish PDF or
|
|
79
|
+
LaTeX versions as I go.
|
|
80
|
+
- Later switch to batch mode to render PDF or LaTeX-ready plots for publication.
|
|
81
|
+
|
|
82
|
+
This toolset was built to support that workflow. It won't do
|
|
83
|
+
everything for you — but it removes a lot of friction.
|
|
84
|
+
|
|
85
|
+
## Requirements
|
|
86
|
+
|
|
87
|
+
- Python 3.10 or newer
|
|
88
|
+
- [gnuplot](http://www.gnuplot.info/) installed and available on your `PATH`
|
|
89
|
+
- Tested with gnuplot 5.4 (check with `gnuplot --version`) on Linux.
|
|
90
|
+
|
|
91
|
+
## Installation
|
|
92
|
+
|
|
93
|
+
```bash
|
|
94
|
+
pip install gnuplot-snippets
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
To try it in a throwaway environment first:
|
|
98
|
+
|
|
99
|
+
```bash
|
|
100
|
+
deactivate 2>/dev/null # exit any active environment
|
|
101
|
+
mkdir -p ~/tmp
|
|
102
|
+
cd ~/tmp
|
|
103
|
+
python3 -m venv ~/tmp/gp-snippets-test
|
|
104
|
+
source ~/tmp/gp-snippets-test/bin/activate
|
|
105
|
+
# On Windows: %USERPROFILE%\tmp\gp-snippets-test\Scripts\activate
|
|
106
|
+
python -m pip install --upgrade pip
|
|
107
|
+
pip install gnuplot-snippets
|
|
108
|
+
|
|
109
|
+
# Check it works:
|
|
110
|
+
pip show -f gnuplot-snippets
|
|
111
|
+
python -c "import gnuplot_snippets; print(gnuplot_snippets.__file__)"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Then run the demo (see [Full demo](#full-demo) below).
|
|
115
|
+
|
|
116
|
+
## Quick example
|
|
117
|
+
|
|
118
|
+
Provide a class a `gnuplot()` method that returns a `GnuplotSnippets`:
|
|
119
|
+
|
|
120
|
+
```python
|
|
121
|
+
from gnuplot_snippets import GnuplotController, GnuplotSnippets
|
|
122
|
+
|
|
123
|
+
class Car:
|
|
124
|
+
|
|
125
|
+
def __init__(self, name, a, b, c):
|
|
126
|
+
self.name, self.a, self.b, self.c = name, a, b, c
|
|
127
|
+
|
|
128
|
+
def gnuplot(self) -> GnuplotSnippets:
|
|
129
|
+
gs = GnuplotSnippets()
|
|
130
|
+
gs.output_to_screen(
|
|
131
|
+
'set terminal qt title "Car Performance"',
|
|
132
|
+
'set xlabel "Time [s]"; set format x',
|
|
133
|
+
'set ylabel "Velocity [m/s]"; set format y "%0.1f"',
|
|
134
|
+
'set y2label "Acceleration [m/s^2]"; set format y2',
|
|
135
|
+
'set ytics nomirror; set y2tics',
|
|
136
|
+
show_source=True) # add source marker to script file
|
|
137
|
+
gs.preplot(
|
|
138
|
+
'fVelocity(t,a,b,c) = a*t**3 + b*t**2 + c*t',
|
|
139
|
+
'fAcceleration(t,a,b,c) = 3.*a*t**2 + 2.*b*t + c',
|
|
140
|
+
f'set title "Performance for {self.name}"',
|
|
141
|
+
show_source=True)
|
|
142
|
+
gs.plot_elements(
|
|
143
|
+
f'fVelocity(x,{self.a},{self.b},{self.c}) title "{self.name}" with lines',
|
|
144
|
+
f'fAcceleration(x,{self.a},{self.b},{self.c}) axis x1y2 title "{self.name} Acceleration" with lines',
|
|
145
|
+
)
|
|
146
|
+
gs.postplot('unset label')
|
|
147
|
+
return gs
|
|
148
|
+
|
|
149
|
+
gc = GnuplotController(script_filename="my_script.gp")
|
|
150
|
+
gs = Car("Car1", 0.01, 0.0001, 0.1).gnuplot()
|
|
151
|
+
|
|
152
|
+
# Note: Args to gc.preplot() are snippets or gnuplot commands.
|
|
153
|
+
# gs.preplot() returns the preplot() snippet string.
|
|
154
|
+
gc.preplot(gs.preplot(), "set xrange[0:15]", "set y2range[0:*]", gs.output_to_screen())
|
|
155
|
+
gc.plot(gs.plot_elements(), pause=4) # wait 4s
|
|
156
|
+
|
|
157
|
+
# Change title and repeat plot with interactive measurement:
|
|
158
|
+
gc.preplot(
|
|
159
|
+
'set title "Interactive Demo. \\nClick in this window, press \'m\' key, then click two points."'
|
|
160
|
+
)
|
|
161
|
+
gc.plot(gs.plot_elements(), pause="mouse_measure") # interactive
|
|
162
|
+
gc.postplot(gs.postplot())
|
|
163
|
+
gc.close()
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
### Notes
|
|
167
|
+
|
|
168
|
+
- The example above uses the `qt` terminal. On Windows, switch to the
|
|
169
|
+
`windows` terminal (see the comment in the demo).
|
|
170
|
+
- Commands are sent to gnuplot in the order you pass them, so later `set`
|
|
171
|
+
commands override earlier ones, just like a normal gnuplot script.
|
|
172
|
+
- Here every command is also written to `my_script.gp`, so you can re-run or
|
|
173
|
+
debug it directly with `gnuplot my_script.gp`.
|
|
174
|
+
|
|
175
|
+
## Full demo
|
|
176
|
+
|
|
177
|
+
The full demo covers plotting to the screen, publishing to a PDF, overlaying
|
|
178
|
+
two objects on one graph, and using the controller directly without snippets
|
|
179
|
+
(including the interactive `mouse_measure` pause). Use it as a template to
|
|
180
|
+
get started.
|
|
181
|
+
|
|
182
|
+
```bash
|
|
183
|
+
python -m gnuplot_snippets.demo
|
|
184
|
+
# OR:
|
|
185
|
+
gnuplot-snippets-demo
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Demo source: https://github.com/neiltemperley/gnuplot-snippets/blob/main/src/gnuplot_snippets/demo.py
|
|
189
|
+
|
|
190
|
+
## Security
|
|
191
|
+
|
|
192
|
+
Snippets are passed to gnuplot verbatim, and gnuplot can run shell commands
|
|
193
|
+
(e.g. via `system`) and write files. Never build snippets from untrusted
|
|
194
|
+
input, and choose safe filenames for script and output files.
|
|
195
|
+
|
|
196
|
+
## License
|
|
197
|
+
|
|
198
|
+
Released under the [MIT License](https://github.com/neiltemperley/gnuplot-snippets/blob/main/LICENSE).
|
|
199
|
+
|
|
200
|
+
## Disclaimer
|
|
201
|
+
|
|
202
|
+
This is an unofficial project and is not affiliated with gnuplot.
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# Useful:
|
|
2
|
+
# poetry check
|
|
3
|
+
# poetry show --outdated
|
|
4
|
+
# toml-sort -i pyproject.toml
|
|
5
|
+
|
|
6
|
+
[build-system]
|
|
7
|
+
requires = ["poetry-core>=2.0.0,<3.0.0"]
|
|
8
|
+
build-backend = "poetry.core.masonry.api"
|
|
9
|
+
|
|
10
|
+
[dependency-groups]
|
|
11
|
+
dev = [
|
|
12
|
+
"pytest>=7.0,<8.0",
|
|
13
|
+
"flake8>=7.3.0,<8.0.0",
|
|
14
|
+
"isort>=9.0.0,<10.0.0"
|
|
15
|
+
]
|
|
16
|
+
|
|
17
|
+
[project]
|
|
18
|
+
name = "gnuplot-snippets"
|
|
19
|
+
version = "0.1.5"
|
|
20
|
+
description = "Composable gnuplot snippets for Python, for interactive and batch plotting by advanced users"
|
|
21
|
+
readme = "README.md"
|
|
22
|
+
license = "MIT"
|
|
23
|
+
license-files = ["LICENSE"]
|
|
24
|
+
authors = [
|
|
25
|
+
{ name = "Neil Temperley" }
|
|
26
|
+
]
|
|
27
|
+
requires-python = ">=3.10"
|
|
28
|
+
dependencies = [
|
|
29
|
+
"pandas>=2.2.3"
|
|
30
|
+
]
|
|
31
|
+
|
|
32
|
+
[project.scripts]
|
|
33
|
+
gnuplot-snippets-demo = "gnuplot_snippets.demo:main"
|
|
34
|
+
|
|
35
|
+
[project.urls]
|
|
36
|
+
Repository = "https://github.com/neiltemperley/gnuplot-snippets"
|
|
37
|
+
Licence = "https://github.com/neiltemperley/gnuplot-snippets/blob/main/LICENSE"
|
|
38
|
+
|
|
39
|
+
[tool.poetry]
|
|
40
|
+
packages = [{ include = "gnuplot_snippets", from = "src" }]
|
|
@@ -0,0 +1,21 @@
|
|
|
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
|
+
"""Composable gnuplot snippets for Python.
|
|
6
|
+
|
|
7
|
+
Typical use::
|
|
8
|
+
from gnuplot_snippets import GnuplotController, GnuplotSnippet, escape_str, format_dataframe, next_datablock_counter
|
|
9
|
+
"""
|
|
10
|
+
from .snippets import GnuplotSnippets, escape_str, format_dataframe, next_datablock_counter
|
|
11
|
+
from .controller import GnuplotController
|
|
12
|
+
|
|
13
|
+
# __all__ defines the public API for "from gnuplot_snippets import *"
|
|
14
|
+
# and signals the public names to IDEs and static tools.
|
|
15
|
+
__all__ = [
|
|
16
|
+
"GnuplotController",
|
|
17
|
+
"GnuplotSnippets",
|
|
18
|
+
"escape_str",
|
|
19
|
+
"format_dataframe",
|
|
20
|
+
"next_datablock_counter",
|
|
21
|
+
]
|
|
@@ -0,0 +1,157 @@
|
|
|
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 sys
|
|
7
|
+
import logging
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Iterable, Iterator
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger("gnuplot_snippets")
|
|
12
|
+
|
|
13
|
+
_TERMINAL_RE = re.compile(r"^\s*set\s+term[inal]*\b", re.IGNORECASE)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _split_top_level(line: str) -> list[str]:
|
|
17
|
+
"""Split one Gnuplot line on ';' outside quotes, braces and comments.
|
|
18
|
+
"""
|
|
19
|
+
segments: list[str] = []
|
|
20
|
+
start, depth, quote, i = 0, 0, "", 0
|
|
21
|
+
while i < len(line):
|
|
22
|
+
ch = line[i]
|
|
23
|
+
if quote:
|
|
24
|
+
if ch == "\\" and quote == '"':
|
|
25
|
+
i += 1 # skip escaped character
|
|
26
|
+
elif ch == quote:
|
|
27
|
+
quote = ""
|
|
28
|
+
elif ch in "\"'":
|
|
29
|
+
quote = ch
|
|
30
|
+
elif ch == "#":
|
|
31
|
+
break # rest of the line is a comment
|
|
32
|
+
elif ch == "{":
|
|
33
|
+
depth += 1
|
|
34
|
+
elif ch == "}":
|
|
35
|
+
depth = max(0, depth - 1)
|
|
36
|
+
elif ch == ";" and depth == 0:
|
|
37
|
+
segments.append(line[start:i])
|
|
38
|
+
start = i + 1
|
|
39
|
+
i += 1
|
|
40
|
+
segments.append(line[start:])
|
|
41
|
+
return segments
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _extract_set_terminal_cmd(*set_cmds: str) -> tuple[str | None, list[str]]:
|
|
45
|
+
"""Find 'set terminal ...' command(s) if it exists in command(s).
|
|
46
|
+
|
|
47
|
+
Commands may be separated by newlines or by semicolons (outside quotes and
|
|
48
|
+
braces). The terminal command is removed from the remaining commands.
|
|
49
|
+
:param set_cmds: Gnuplot commands
|
|
50
|
+
:returns: tuple of set terminal command, list of remaining command lines.
|
|
51
|
+
"""
|
|
52
|
+
lines: list[str] = []
|
|
53
|
+
terms: list[str] = []
|
|
54
|
+
for cmd in set_cmds:
|
|
55
|
+
for line in cmd.splitlines():
|
|
56
|
+
if not line.strip():
|
|
57
|
+
continue
|
|
58
|
+
kept: list[str] = []
|
|
59
|
+
for seg in _split_top_level(line):
|
|
60
|
+
if _TERMINAL_RE.match(seg):
|
|
61
|
+
terms.append(seg.strip())
|
|
62
|
+
elif seg.strip():
|
|
63
|
+
kept.append(seg.strip())
|
|
64
|
+
if kept:
|
|
65
|
+
lines.append("; ".join(kept))
|
|
66
|
+
if len(terms) > 1:
|
|
67
|
+
raise ValueError(
|
|
68
|
+
f"More than one 'set terminal' command given: {terms}.")
|
|
69
|
+
return (terms[0] if terms else None), lines
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _source(note: str = "", is_snippet: bool = True, depth: int = 2) -> str:
|
|
73
|
+
"""Create a comment string identifying the source of a gnuplot command.
|
|
74
|
+
|
|
75
|
+
Reports the location ``depth`` frames above this function. The default of 2
|
|
76
|
+
is the caller of the function that called ``_source``, i.e. the user's code
|
|
77
|
+
when called from a public GnuplotSnippets or GnuplotController method.
|
|
78
|
+
|
|
79
|
+
Note: No newline at end.
|
|
80
|
+
:param note: optional note to append. Newlines are converted to comment lines.
|
|
81
|
+
:param is_snippet: True if called from a GnuplotSnippets method, else GnuplotController.
|
|
82
|
+
:param depth: number of frames to walk up from this function.
|
|
83
|
+
:returns: Source string to write to the gnuplot script file.
|
|
84
|
+
"""
|
|
85
|
+
source_type = "GnuplotSnippets" if is_snippet else "GnuplotController"
|
|
86
|
+
note = note.replace("\n", "\n# ")
|
|
87
|
+
try:
|
|
88
|
+
frame = sys._getframe(depth)
|
|
89
|
+
except (ValueError, AttributeError): # stack too shallow / non-CPython
|
|
90
|
+
return f"{source_type} Source unknown. {note}"
|
|
91
|
+
filename = frame.f_code.co_filename
|
|
92
|
+
return f"{source_type} Source: {filename}: {frame.f_lineno}: {frame.f_code.co_name}()... {note}"
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _flatten_to_tuple_of_strings(*args) -> tuple[str, ...]:
|
|
96
|
+
"""Flatten strings and arbitrarily nested iterables of strings.
|
|
97
|
+
|
|
98
|
+
Accepts str, or any iterable (tuple, list, generator, ...) of those, nested to any depth.
|
|
99
|
+
Empty strings are dropped, since plot elements cannot be empty.
|
|
100
|
+
|
|
101
|
+
:raises TypeError: if any item is neither a str nor an iterable.
|
|
102
|
+
:returns: tuple of strings
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
106
|
+
def _flatten(item) -> Iterator[str]:
|
|
107
|
+
if isinstance(item, str):
|
|
108
|
+
yield item
|
|
109
|
+
elif isinstance(item, (bytes, dict)):
|
|
110
|
+
raise TypeError(
|
|
111
|
+
f"plot elements cannot contain {type(item).__name__}")
|
|
112
|
+
elif isinstance(item, Iterable):
|
|
113
|
+
for sub in item:
|
|
114
|
+
yield from _flatten(sub)
|
|
115
|
+
else:
|
|
116
|
+
raise TypeError(
|
|
117
|
+
f"plot elements must be str or iterable of str, got {type(item).__name__}: {item!r}!"
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
# ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
|
|
121
|
+
|
|
122
|
+
return tuple(s for s in _flatten(args) if s.strip())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _check_cmd(cmd):
|
|
126
|
+
"""Check cmd is a string."""
|
|
127
|
+
if not isinstance(cmd, str):
|
|
128
|
+
if type(cmd).__name__ == "GnuplotSnippets":
|
|
129
|
+
raise TypeError(
|
|
130
|
+
f"Expected string, got {type(cmd).__name__}: {cmd!r}.\n"
|
|
131
|
+
"Perhaps you sent a snippets object to preplot()? To add a snippet use the snippets' append() method."
|
|
132
|
+
)
|
|
133
|
+
else:
|
|
134
|
+
raise TypeError(
|
|
135
|
+
f"Expected a string; got {type(cmd).__name__}: {cmd!r}.")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _clean_cmds(*set_cmds) -> str:
|
|
140
|
+
"""Clean and add one or more lines to the gnuplot command string.
|
|
141
|
+
|
|
142
|
+
Attempts to comment out any "pause XXX" gnuplot commands of user because
|
|
143
|
+
the GnuplotController will handle the pause workflow.
|
|
144
|
+
:raises TypeError: if any argument is not a string
|
|
145
|
+
:returns: cleaned up command string always ending with a newline unless empty.
|
|
146
|
+
"""
|
|
147
|
+
lines: list[str] = []
|
|
148
|
+
for cmd in set_cmds:
|
|
149
|
+
_check_cmd(cmd)
|
|
150
|
+
for line in cmd.splitlines():
|
|
151
|
+
# logger.debug("line \t= \"{}\"".format(line))
|
|
152
|
+
# Replace 'pause -1', 'pause mouse' with '# pause 0' etc.
|
|
153
|
+
new_line = re.sub(r'\bpause\s+(-?\d+|mouse)([^;\n]*)[;]*',
|
|
154
|
+
r'# pause \1\2\n', line)
|
|
155
|
+
# logger.debug("new_line \t= \"{}\"".format(new_line))
|
|
156
|
+
lines.append(new_line.rstrip())
|
|
157
|
+
return "\n".join(lines) + "\n" if len(lines) > 0 else ""
|