Last active
February 28, 2023 23:46
-
-
Save alanbernstein/a178fa96b355cc69ea249b688d9dd3a0 to your computer and use it in GitHub Desktop.
Matplotlib PersistentFigure prototype
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{"alans-desktop-some-script.py-main-Figure 1": [2485, 231, 1054, 862]} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
import json | |
import os | |
import socket | |
import matplotlib.pyplot as plt | |
class PersistentFigure(object): | |
def __init__(self, *args, **kwargs): | |
self.data_file = os.getcwd() + '/mplpersist.json' | |
self.hostname = socket.gethostname() | |
frames = inspect.getouterframes(inspect.currentframe()) | |
self.parent_file = frames[1].filename | |
self.parent_function = frames[1].function | |
if not os.path.exists(self.data_file): | |
with open(self.data_file, 'w') as f: | |
json.dump({}, f) | |
# set up figure window | |
self.figure = plt.figure(*args, **kwargs) | |
self.mngr = plt.get_current_fig_manager() | |
self.figure_title = self.mngr.get_window_title() | |
# manage geometry | |
self.key = '%s-%s-%s-%s' % (self.hostname, self.parent_file, self.parent_function, self.figure_title) | |
geom = self._load_geometry() | |
if geom: | |
self.mngr.window.setGeometry(*geom) | |
# connect callback | |
cid = self.figure.canvas.mpl_connect('resize_event', self._on_resize) | |
def _save_geometry(self): | |
geom = self.mngr.window.geometry() | |
g = geom.getRect() | |
with open(self.data_file, 'r') as f: | |
data = json.load(f) | |
data[self.key] = g | |
with open(self.data_file, 'w') as f: | |
json.dump(data, f) | |
def _load_geometry(self): | |
if not os.path.exists(self.data_file): | |
print('mpltools.fig.load_geometry_flat: file not found') | |
return None | |
with open(self.data_file, 'r') as f: | |
data = json.load(f) | |
return data.get(self.key, None) | |
def _on_resize(self, ev): | |
self._save_geometry() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
from persist import PersistentFigure as fig | |
def main(): | |
f = fig() | |
plt.plot([1, 2, 3], [6, 5, 4]) | |
plt.show() | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment