Erfassen von Matplotlib -Figur, wenn sie in Jupyter Notebook gezeigt werdenPython

Python-Programme
Anonymous
 Erfassen von Matplotlib -Figur, wenn sie in Jupyter Notebook gezeigt werden

Post by Anonymous »

Ich schreibe diese Helferklasse, um die Ausgänge (sowohl Text- als auch Matplotlib -Abbildungen) einer Jupyter -Notebook -Zelle in eine HTML -Datei zu speichern. < /P>

Code: Select all

class CaptureToHTML:
def __init__(self, html_file: str):
self._html_file = html_file
self._original_print = builtins.print
self.output = []  # Stores ('print', args) and ('figure', fig) items

def _wrapped_print(self, *args, **kwargs):
self.output.append(('print', args))
self._original_print(*args, **kwargs)

def capture_current_figure(self):
"""
Call this method *before* plt.show() to capture the current figure.
"""
fig = plt.gcf()
self.output.append(('figure', fig))

def __enter__(self):
builtins.print = self._wrapped_print
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.flush()
builtins.print = self._original_print

def _figure_to_base64(self, figure):
img_buffer = io.BytesIO()
figure.savefig(img_buffer, format='png')
img_buffer.seek(0)
img_str = base64.b64encode(img_buffer.read()).decode('utf-8')
return img_str

def flush(self):
directory = os.path.dirname(self._html_file)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)

with open(self._html_file, 'a') as f:
datetime_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
f.write(f"Captured at {datetime_str}\n")

for item in self.output:
if item[0] == 'print':
f.write(f"
{' '.join(map(str, item[1]))}
\n")
elif item[0] == 'figure':
img_str = self._figure_to_base64(item[1])
f.write(f'
[img]data:image/png;base64,{img_str}[/img]
\n')

f.write("\n")
< /code>
Die Art und Weise, wie dies derzeit verwendet wird, ist wie in: < /p>
with CaptureToHTML("out.html") as capture:
print("Starting experiment...")
for i in range(3):
print(f"Scan {i+1}\n")
plt.figure()
plt.plot([1, 2, 3], [j * (i+1) for j in [1, 2, 3]])
plt.title(f"Plot {i+1}")

capture.capture_current_figure()
plt.show()
< /code>
Ich möchte, dass der Erfassungsvorgang automatisch stattfindet. Zu diesem Zweck habe ich versucht, die PLT.Show () 
-Methode zu wickeln und die Abbildung dort abzufangen. Dies wirft jedoch einige der Zeiten nur einige Zeiten auf: < /p>

Code: Select all

AttributeError                            Traceback (most recent call last)
Cell In[1], line 153
151 print(f"Scan {i+1}\n")
--> 153 plt.figure()
155 plt.plot([1, 2, 3], [j * (i+1) for j in [1, 2, 3]])

File [...]/pyplot.py:1042, in figure(num, figsize, dpi, facecolor, edgecolor, frameon, FigureClass, clear, **kwargs)
1032 if len(allnums) == max_open_warning >= 1:
1033     _api.warn_external(
1034         f"More than {max_open_warning} figures have been opened. "
1035         f"Figures created through the pyplot interface "
(...)
1039         f"Consider using matplotlib.pyplot.close().",
1040         RuntimeWarning)
-> 1042 manager = new_figure_manager(
1043     num, figsize=figsize, dpi=dpi,
1044     facecolor=facecolor, edgecolor=edgecolor, frameon=frameon,
1045     FigureClass=FigureClass, **kwargs)
1046 fig = manager.canvas.figure
1047 if fig_label:

File [...]/pyplot.py:551, in new_figure_manager(*args, **kwargs)
...
518 # Need to keep a global reference to the backend for compatibility reasons.
519 # See https://github.com/matplotlib/matplotlib/issues/6092
520 matplotlib.backends.backend = newbackend  # type: ignore[attr-defined]

AttributeError: 'method' object has no attribute '__signature__'
Danke für Ihre Hilfe.

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post