-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathPlotLayout.py
324 lines (247 loc) · 10.1 KB
/
PlotLayout.py
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
import pylab
from matplotlib import pyplot
import os
import warnings
from boomslang_exceptions import BoomslangPlotRenderingException
from Utils import getGoldenRatioDimensions, _check_min_matplotlib_version
class PlotLayout(object):
"""
Displays multiple :class:`boomslang.Plot.Plot` objects in one canvas in a
grid, allowing the user to group related Plots in the same row.
"""
def __init__(self):
self.groupedPlots = {}
self.plots = []
self.groupOrder = None
"""
If not None, a list of groups in order by the order in which they
should be displayed
"""
self._width = 1
self.plotParams = None
self.dimensions = None
self.figdimensions = None
self.dpi = None
self.figLegendLoc = None
self.figLegendCols = None
self.rcParams = None
self.tight = True
def __setRCParam(self, param, value):
if self.rcParams is None:
self.rcParams = {}
self.rcParams[param] = value
def setTitleSize(self, size):
self.__setRCParam("axes.titlesize", size)
def useLatexLabels(self):
warnings.warn("WARNING: Using LaTeX labels requires dvipng and "
"ghostscript")
self.__setRCParam("text.usetex", True)
def setAxesLabelSize(self, size):
self.__setRCParam("axes.labelsize", size)
def setXTickLabelSize(self, size):
self.__setRCParam("xtick.labelsize", size)
def setYTickLabelSize(self, size):
self.__setRCParam("ytick.labelsize", size)
def setLegendLabelSize(self, size):
self.__setRCParam("legend.fontsize", size)
def setWidth(self, width):
self.width = int(width)
@property
def width(self):
"""
The width, in number of plots, of the layout.
"""
return self._width
@width.setter
def width(self, width):
self._width = int(width)
def hasFigLegend(self, loc="best", columns=1, numcols=None):
if numcols is not None:
# hasLegend uses columns, rather than numcols.
# trying to make this consistent.
# this should catch named parameter usage
columns = numcols
warnings.warn("numcols deprecated for hasFigLegend", Warning)
self.figLegendLoc = loc
self.figLegendCols = columns
def addPlot(self, plot, grouping=None):
"""
Add `plot` (a :class:`boomslang.Plot.Plot`) to the layout. Optionally,
specify a group name with `grouping`. Plots grouped in the same
grouping are drawn on the same row of the grid.
"""
if not plot.allows_tight:
self.tight = False
if grouping == None:
self.plots.append(plot)
else:
if grouping not in self.groupedPlots:
self.groupedPlots[grouping] = []
self.groupedPlots[grouping].append(plot)
def setGroupOrder(self, groupOrder):
self.groupOrder = groupOrder
def setPlotDimensions(self, x, y, dpi=100):
"""
Set the dimensions of each plot in the layout to be `x` by `y`.
"""
self.dimensions = (x,y)
self.dpi = dpi
def setFigureDimensions(self, x, y, dpi=100):
"""
Set the dimensions of the layout to be `x` by `y`. This overrides any
values set with
:py:func:`boomslang.PlotLayout.PlotLayout.setPlotDimensions`.
"""
self.figdimensions = (x,y)
self.dpi = dpi
def setPlotParameters(self, **kwdict):
self.plotParams = dict(kwdict)
if "left" not in self.plotParams:
self.plotParams["left"] = 0.12
if "bottom" not in self.plotParams:
self.plotParams["bottom"] = 0.10
if "right" not in self.plotParams:
self.plotParams["right"] = 0.90
if "top" not in self.plotParams:
self.plotParams["top"] = 0.90
if "wspace" not in self.plotParams:
self.plotParams["wspace"] = 0.20
if "hspace" not in self.plotParams:
self.plotParams["hspace"] = 0.20
def _doPlot(self):
if len(self.groupedPlots) + len(self.plots) == 0:
raise BoomslangPlotRenderingException("No data to plot!")
oldRCParams = {}
if self.rcParams is not None:
for (param, value) in self.rcParams.items():
oldRCParams[param] = pylab.rcParams[param]
pylab.rcParams[param] = value
groupedPlotLengths = [len(plots) for plots in self.groupedPlots.values()]
if len(groupedPlotLengths) == 0:
maxRowLength = self.width
else:
maxRowLength = max(groupedPlotLengths)
numPlots = len(self.plots)
if numPlots == 0:
numExcessRows = 0
elif numPlots <= maxRowLength:
numExcessRows = 1
elif numPlots % maxRowLength == 0:
numExcessRows = numPlots / maxRowLength
else:
numExcessRows = (numPlots / maxRowLength) + 1
numRows = len(self.groupedPlots.keys()) + numExcessRows
if self.groupOrder is not None:
keyList = self.groupOrder
else:
keyList = self.groupedPlots.keys()
currentRow = 0
if self.figdimensions is not None:
fig = pyplot.figure(figsize=(self.figdimensions[0],
self.figdimensions[1]))
elif self.dimensions is not None:
fig = pyplot.figure(figsize=(self.dimensions[0] * maxRowLength,
self.dimensions[1] * numRows))
else:
(figWidth, figHeight) = getGoldenRatioDimensions(8.0)
figWidth *= maxRowLength
figHeight *= numRows
fig = pyplot.figure(figsize=(figWidth, figHeight))
plotHandles = []
plotLabels = []
for grouping in keyList:
currentColumn = 1
plots = self.groupedPlots[grouping]
numPlots = len(plots)
for plot in plots:
myRows = numRows
myCols = numPlots
myPos = (currentRow * numPlots) + currentColumn
(currPlotHandles, currPlotLabels) = self._plot_subplot(
plot = plot, fig = fig, rows = myRows, cols = myCols,
pos = myPos, projection=plot.projection)
for i in xrange(len(currPlotHandles)):
if currPlotLabels[i] in plotLabels:
continue
if isinstance(currPlotHandles[i], list):
plotHandles.append(currPlotHandles[i][0])
else:
plotHandles.append(currPlotHandles[i])
plotLabels.append(currPlotLabels[i])
currentColumn += 1
currentRow += 1
ungroupedPlotsRemaining = len(self.plots)
if ungroupedPlotsRemaining > 0:
currentColumn = 1
for plot in self.plots:
if currentColumn == 1:
numColumns = min(maxRowLength, ungroupedPlotsRemaining)
myRows = numRows
myCols = numColumns
myPos = (currentRow * numColumns) + currentColumn
(currPlotHandles, currPlotLabels) = self._plot_subplot(
plot = plot, fig = fig, rows = myRows, cols = myCols,
pos = myPos, projection=plot.projection)
for i in xrange(len(currPlotHandles)):
if currPlotLabels[i] in plotLabels:
continue
if isinstance(currPlotHandles[i], list):
plotHandles.append(currPlotHandles[i][0])
else:
plotHandles.append(currPlotHandles[i])
plotLabels.append(currPlotLabels[i])
currentColumn += 1
if currentColumn > numColumns:
currentRow += 1
currentColumn = 1
ungroupedPlotsRemaining -= 1
if self.figLegendLoc is not None:
figLegendKeywords = {}
if self.figLegendCols is not None:
if not _check_min_matplotlib_version(0, 98, 0):
warnings.warn("Number of columns support not available in "
"versions of matplotlib prior to 0.98")
else:
figLegendKeywords["ncol"] = self.figLegendCols
fig.legend(plotHandles, plotLabels,
self.figLegendLoc,
**figLegendKeywords)
if self.plotParams is not None:
fig.subplots_adjust(left=self.plotParams["left"],
bottom=self.plotParams["bottom"],
right=self.plotParams["right"],
top=self.plotParams["top"],
wspace=self.plotParams["wspace"],
hspace=self.plotParams["hspace"])
# Restore old RC params
for (key,value) in oldRCParams.items():
pylab.rcParams[key] = value
if _check_min_matplotlib_version(1, 1, 0) and self.tight:
fig.tight_layout()
return fig
def _plot_subplot(self, plot, fig, rows, cols, pos, projection):
return plot.subplot(fig, rows, cols, pos, projection)
def plot(self):
"""
Draw this layout to a matplotlib canvas.
"""
fig = self._doPlot()
if not pylab.isinteractive():
pylab.show()
else:
pylab.draw()
pylab.close(fig)
def save(self, filename, **kwargs):
"""
Save this layout to a file.
"""
tempDisplayHack = False
if "DISPLAY" not in os.environ:
tempDisplayHack = True
os.environ["DISPLAY"] = ":0.0"
fig = self._doPlot()
fig.savefig(filename, dpi = self.dpi, **kwargs)
# pylab holds on to all figures unless you explicitly close them
pylab.close(fig)
if tempDisplayHack == True:
del os.environ["DISPLAY"]