-
Notifications
You must be signed in to change notification settings - Fork 252
Expand file tree
/
Copy pathcontext.py
More file actions
157 lines (122 loc) · 4.1 KB
/
Copy pathcontext.py
File metadata and controls
157 lines (122 loc) · 4.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
from __future__ import annotations
from copy import copy, deepcopy
from dataclasses import dataclass
from typing import TYPE_CHECKING
import pandas as pd
from packaging.version import Version
from ..session import set_last_plot
if TYPE_CHECKING:
from typing_extensions import Self
from plotnine import ggplot
from plotnine.composition import Compose
PANDAS_LT_3 = Version(pd.__version__) < Version("3.0")
def reopen(fig):
"""
Reopen an MPL figure that has been closed with plt.close
When drawing compositions, plot_composition_context will nest
plot_context. In this case, plot_context may close an MPL figure
that belongs to composition. A closed figure cannot be shown with
plt.show, so for compositions compose.show (if called) will do nothing.
"""
from matplotlib._pylab_helpers import Gcf
Gcf.set_active(fig.canvas.manager)
def is_closed(fig) -> bool:
"""
Return True if figure is closed
"""
import matplotlib.pyplot as plt
return not plt.fignum_exists(fig.number)
@dataclass
class plot_context:
"""
Context within which the plot is built
Parameters
----------
plot :
ggplot object to be built within the context.
show :
Whether to show the plot.
"""
plot: ggplot
show: bool = False
def __post_init__(self):
import matplotlib as mpl
# Contexts
self.rc_context = mpl.rc_context(self.plot.theme.rcParams)
if PANDAS_LT_3:
self.pd_option_context = pd.option_context(
"mode.copy_on_write",
True,
)
def __enter__(self) -> Self:
"""
Enclose in matplolib & pandas environments
"""
self._last_plot = deepcopy(self.plot)
self.rc_context.__enter__()
if PANDAS_LT_3:
self.pd_option_context.__enter__()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
"""
Exit matplotlib & pandas environments
"""
import matplotlib.pyplot as plt
if exc_type is None:
if self.show:
plt.show()
else:
plt.close(self.plot.figure)
set_last_plot(self._last_plot)
else:
# There is an exception, close any figure
if hasattr(self.plot, "figure"):
plt.close(self.plot.figure)
self.rc_context.__exit__(exc_type, exc_value, exc_traceback)
if PANDAS_LT_3:
self.pd_option_context.__exit__(exc_type, exc_value, exc_traceback)
@dataclass
class plot_composition_context:
"""
Context within which a plot composition is built
Parameters
----------
cmp :
composition object to be built within the context.
show :
Whether to show the plot.
"""
cmp: Compose
show: bool
def __post_init__(self):
import matplotlib as mpl
# The dpi is needed when the figure is created, either as
# a parameter to plt.figure() or an rcParam.
# https://github.com/matplotlib/matplotlib/issues/24644
# When drawing the Composition, the dpi themeable is infective
# because it sets the rcParam after this figure is created.
self._rc_context = mpl.rc_context(
{"figure.dpi": self.cmp.theme.getp("dpi")}
)
def __enter__(self) -> Self:
"""
Enclose in matplolib & pandas environments
"""
self._last_plot = copy(self.cmp)
self._rc_context.__enter__()
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
import matplotlib.pyplot as plt
if exc_type is None:
if self.show:
if is_closed(self.cmp.figure):
reopen(self.cmp.figure)
plt.show()
else:
plt.close(self.cmp.figure)
set_last_plot(self._last_plot)
else:
# There is an exception, close any figure
if hasattr(self.cmp, "figure"):
plt.close(self.cmp.figure)
self._rc_context.__exit__(exc_type, exc_value, exc_traceback)