11from __future__ import annotations
22
3+ from copy import copy
34from dataclasses import dataclass
45from typing import TYPE_CHECKING
56
67import pandas as pd
78from packaging .version import Version
89
10+ from ..session import set_last_plot
11+
912if TYPE_CHECKING :
1013 from typing_extensions import Self
1114
@@ -38,6 +41,7 @@ def is_closed(fig) -> bool:
3841 return not plt .fignum_exists (fig .number )
3942
4043
44+ @dataclass
4145class plot_context :
4246 """
4347 Context within which the plot is built
@@ -50,14 +54,14 @@ class plot_context:
5054 Whether to show the plot.
5155 """
5256
53- def __init__ ( self , plot : ggplot , show : bool = False ):
54- import matplotlib as mpl
57+ plot : ggplot
58+ show : bool = False
5559
56- self . plot = plot
57- self . show = show
60+ def __post_init__ ( self ):
61+ import matplotlib as mpl
5862
5963 # Contexts
60- self .rc_context = mpl .rc_context (plot .theme .rcParams )
64+ self .rc_context = mpl .rc_context (self . plot .theme .rcParams )
6165 if PANDAS_LT_3 :
6266 self .pd_option_context = pd .option_context (
6367 "mode.copy_on_write" ,
@@ -69,6 +73,7 @@ def __enter__(self) -> Self:
6973 Enclose in matplolib & pandas environments
7074 """
7175
76+ self ._last_plot = copy (self .plot )
7277 self .rc_context .__enter__ ()
7378 if PANDAS_LT_3 :
7479 self .pd_option_context .__enter__ ()
@@ -86,6 +91,7 @@ def __exit__(self, exc_type, exc_value, exc_traceback):
8691 plt .show ()
8792 else :
8893 plt .close (self .plot .figure )
94+ set_last_plot (self ._last_plot )
8995 else :
9096 # There is an exception, close any figure
9197 if hasattr (self .plot , "figure" ):
@@ -127,6 +133,7 @@ def __enter__(self) -> Self:
127133 """
128134 Enclose in matplolib & pandas environments
129135 """
136+ self ._last_plot = copy (self .cmp )
130137 self ._rc_context .__enter__ ()
131138 return self
132139
@@ -140,6 +147,7 @@ def __exit__(self, exc_type, exc_value, exc_traceback):
140147 plt .show ()
141148 else :
142149 plt .close (self .cmp .figure )
150+ set_last_plot (self ._last_plot )
143151 else :
144152 # There is an exception, close any figure
145153 if hasattr (self .cmp , "figure" ):
0 commit comments