-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathfigure.py
More file actions
374 lines (300 loc) · 12.7 KB
/
figure.py
File metadata and controls
374 lines (300 loc) · 12.7 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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# -*- coding: utf-8 -*-
from vplanet import Quantity
import matplotlib
import matplotlib.pyplot
from matplotlib.figure import Figure
from matplotlib.axes import Axes
import astropy.units as u
def _get_array_info(array, max_label_length=40):
if hasattr(array, "unit") and hasattr(array, "tags"):
if array.unit.physical_type != array.tags.get(
"physical_type", array.unit.physical_type
):
# The physical type of this array changed, so this is
# no longer the original VPLANET quantity!
unit = str(array.unit)
if unit == "":
unit = None
body = None
label = None
physical_type = array.unit.physical_type
if physical_type == "Dimensionless":
physical_type = None
else:
unit = str(array.unit)
if unit == "":
unit = None
body = array.tags.get("body", None)
label = array.tags.get("description", None)
if label is not None and len(label) > max_label_length:
label = array.tags.get("name", None)
physical_type = array.unit.physical_type
if physical_type == "Dimensionless":
physical_type = None
else:
unit = None
body = None
label = None
physical_type = None
return unit, body, label, physical_type
class VPLOTFigure(Figure):
"""A ``vplot`` figure object, a subclass of :py:class:`matplotlib.figure.Figure`.
This class adds certain functionality to the default ``matplotlib`` figure
object, in particular the ability to recognize when ``vplanet`` quantities
are plotted. When showing / drawing / saving the figure, this class will
automatically label the axes and/or add a legend with the appropriate
parameter names, types, units, and corresponding ``vplanet`` body. All of
these can be overridden by setting the axes or legend labels explcitly.
This class accepts all args and kwargs as :py:class:`matplotlib.figure.Figure`,
with support for the following additional keywords:
Args:
max_label_length (int, optional): If the parameter description is longer
than this value, the axis will be labeled with the shorter parameter
name instead. Default 40.
mpl_units (bool, optional): Enable matplotlib units functionality? Default
is True. This allows quantities of the same physical type but different
units (such as ``yr`` and ``Gyr``) to be plotted on the same axis;
this class will handle unit conversions as needed. An error will be
raised if the unit conversion fails.
xlog (bool, optional): Set the x axis scale to be logarithmic? Default False.
ylog (bool, optional): Set the y axis scale to be logarithmic? Default False.
"""
def __init__(
self,
*args,
max_label_length=40,
mpl_units=True,
xlog=False,
ylog=False,
auto_legend=True,
**kwargs
):
# Parameters
self.max_label_length = max_label_length
self.xlog = xlog
self.ylog = ylog
self.auto_legend = auto_legend
# Enable astropy/matplotlib quantity support? (Recommended)
if mpl_units:
from vplanet.quantity_support import quantity_support
quantity_support()
super().__init__(*args, **kwargs)
# Watch the axes
self._update_on_draw = True
self.add_axobserver(self._ax_observer)
def _ax_observer(self, *args):
# Force an update next time we draw
self._update_on_draw = True
# HACK: Override `ax.scatter` so that we preserve the
# metadata in the Quantity arrays, as `scatter` converts
# them to numpy masked arrays. I couldn't find a
# simple way to subclass `Axes` or `Subplots` to directly
# replace the `scatter` method, so we'll go with this for now.
for ax in self.axes:
# Mark it so we don't do it repeatedly
if hasattr(ax, "__vplot__"):
continue
else:
ax.__vplot__ = True
old_scatter = ax.scatter
def new_scatter(x, y, *args, **kwargs):
collection = old_scatter(x, y, *args, **kwargs)
def get_data():
return Quantity(x), Quantity(y)
get_data.__vplot__ = True
collection.get_data = get_data
return collection
ax.scatter = new_scatter
# TODO: Override ax.imshow as well so we can
# automatically add units to colorbars.
def _add_labels(self):
# Get the labels for each axis
for k, ax in enumerate(self.axes):
# Skip if there's no data to parse
if len(ax.lines) == 0 and len(ax.collections) == 0:
continue
# Check if there are labels already
xlabel_exists = not (
ax.get_xlabel() is None or ax.get_xlabel() == ""
)
ylabel_exists = not (
ax.get_ylabel() is None or ax.get_ylabel() == ""
)
legend_exists = ax.get_legend() is not None
# Skip if the user already set these
if xlabel_exists and ylabel_exists and legend_exists:
continue
# Get info on all lines in the axis
xunits = []
xlabels = []
xtypes = []
yunits = []
ylabels = []
ytypes = []
bodies = []
lines = [
line
for line in ax.lines + ax.collections
if hasattr(line, "get_data")
]
for line in lines:
# Get the data
x, y = line.get_data()
# Grab the x metadata
unit, _, label, physical_type = _get_array_info(
x, self.max_label_length
)
xunits.append(unit)
xlabels.append(label)
xtypes.append(physical_type)
# Grab the y metadata
unit, body, label, physical_type = _get_array_info(
y, self.max_label_length
)
yunits.append(unit)
ylabels.append(label)
ytypes.append(physical_type)
bodies.append(body)
# Figure out the x physical type
if len(set(xtypes)) == 0:
xtype = None
elif len(set(xtypes)) == 1:
xtype = xtypes[0]
elif len(set(xtypes)) == 2 and None in xtypes:
# Allow unitless quantities to be shown on the same
# axis as unitful quantities, since matplotlib.units allows it
xtype = [xtype for xtype in xtypes if xtype is not None][0]
else:
raise ValueError(
"Axis #{} contains quantities with different physical types: {}".format(
k + 1, ", ".join(xtypes)
)
)
# Figure out the y physical type
if len(set(ytypes)) == 0:
ytype = None
elif len(set(ytypes)) == 1:
ytype = ytypes[0]
elif len(set(ytypes)) == 2 and None in ytypes:
# Allow unitless quantities to be shown on the same
# axis as unitful quantities, since matplotlib.units allows it
ytype = [ytype for ytype in ytypes if ytype is not None][0]
else:
raise ValueError(
"Axis #{} contains quantities with different physical types: {}".format(
k + 1, ", ".join(ytypes)
)
)
# Figure out the x unit
if len(set(xunits)) == 0:
xunit = None
elif len(set(xunits)) == 1:
if xunits[0] is None:
xunit = None
else:
xunit = str(xunits[0])
elif len(set(xunits)) > 1:
xunit = None
for xunit in set(xunits):
if xunit is not None:
# A hacky way to figure out the actual unit
if ax.convert_xunits(1 * u.Unit(xunit)) == 1:
break
# Figure out the y unit
if len(set(yunits)) == 0:
yunit = None
elif len(set(yunits)) == 1:
if yunits[0] is None:
yunit = None
else:
yunit = str(yunits[0])
elif len(set(yunits)) > 1:
yunit = None
for yunit in set(yunits):
if yunit is not None:
# A hacky way to figure out the actual unit
if ax.convert_yunits(1 * u.Unit(yunit)) == 1:
break
# Are we dealing with single bodies/quantity types?
single_body = len(set(bodies)) == 1 and bodies[0] is not None
single_xparam = len(set(xlabels)) == 1 and xlabels[0] is not None
single_yparam = len(set(ylabels)) == 1 and ylabels[0] is not None
# Add the x axis label
if not xlabel_exists:
xlabel = ""
if single_xparam:
xlabel += "{}".format(xlabels[0])
elif xtype is not None:
xlabel += "{}".format(xtype)
if xunit is not None:
xlabel += " [{}]".format(xunit)
if xlabel.endswith(": "):
xlabel = xlabel[:-2]
ax.set_xlabel(xlabel)
# Add the y axis label
if not ylabel_exists:
ylabel = ""
if single_body:
ylabel += "{}: ".format(bodies[0])
if single_yparam:
ylabel += "{}".format(ylabels[0])
elif ytype is not None:
ylabel += "{}".format(ytype)
if yunit is not None:
ylabel += " [{}]".format(yunit)
if ylabel.endswith(": "):
ylabel = ylabel[:-2]
ax.set_ylabel(ylabel)
# Add the legend
if self.auto_legend and not legend_exists:
make_legend = False
for j, line in enumerate(lines):
if (
line.get_label() is None
or line.get_label() == ""
or line.get_label().startswith("_line")
or line.get_label().startswith("_collection")
or line.get_label().startswith("_child")
):
label = ""
if not single_body and bodies[j] is not None:
label += "{}: ".format(bodies[j])
if not single_yparam:
if ylabels[j] is not None:
label += "{}".format(ylabels[j])
elif ytype is not None:
label += "{}".format(ytype)
if label.endswith(": "):
label = label[:-2]
if label != "":
line.set_label(label)
make_legend = True
if make_legend:
ax.legend(loc="best")
def _format_axes(self):
for ax in self.axes:
# Force time axis margins to be zero
if "Time" in ax.get_xlabel():
ax.margins(0, ax.margins()[1])
# Make axes logarithmic?
if self.xlog:
ax.set_xscale("log")
if self.ylog:
ax.set_yscale("log")
def draw(self, *args, **kwargs):
if self._update_on_draw:
self._add_labels()
self._format_axes()
self.tight_layout()
self._update_on_draw = False
super().draw(*args, **kwargs)
# HACK: Override `Figure` so this will work seamlessly in the background
matplotlib.figure.Figure = VPLOTFigure
# HACK: We need to explicitly override `plt.figure` since its default
# kwarg for `FigureClass` is `matplotlib.figure.Figure`. This default
# value is parsed on **import**, so if the user imported `pyplot`
# before `vplot`, the default figure class will still be the old one.
mpl_figure = matplotlib.pyplot.figure
def figure_wrapper(*args, FigureClass=VPLOTFigure, **kwargs):
return mpl_figure(*args, FigureClass=VPLOTFigure, **kwargs)
matplotlib.pyplot.figure = figure_wrapper