Skip to content

Commit 499e61b

Browse files
committed
Adjust title and legend spaces, esp. for facets
It is still not perfect.
1 parent a2879f5 commit 499e61b

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

ggplot/ggplot.py

+23-8
Original file line numberDiff line numberDiff line change
@@ -291,15 +291,19 @@ def draw_legend(self, plot):
291291
return plot
292292

293293
position = plot.theme._params['legend_position']
294+
294295
# At what point (e.g [.94, .5]) on the figure
295296
# to place which point (e.g 6, for center left) of
296297
# the legend box
298+
_x = 0.92
299+
# Prevent overlap with the facet label
300+
if isinstance(plot.facet, facet_grid):
301+
_x += .025 * len(plot.facet.rows)
297302
lookup = {
298-
'right': (6, (0.92, 0.5)), # center left
303+
'right': (6, (_x, 0.5)), # center left
299304
'left': (7, (0.07, 0.5)), # center right
300305
'top': (8, (0.5, 0.92)), # bottom center
301-
'bottom': (9, (0.5, 0.07)) # upper center
302-
}
306+
'bottom': (9, (0.5, 0.07))} # upper center
303307
loc, box_to_anchor = lookup[position]
304308
anchored_box = AnchoredOffsetbox(
305309
loc=loc,
@@ -309,8 +313,8 @@ def draw_legend(self, plot):
309313
# Spacing goes here
310314
bbox_to_anchor=box_to_anchor,
311315
bbox_transform=plot.figure.transFigure,
312-
borderpad=0.,
313-
)
316+
borderpad=0.)
317+
314318
plot.figure._themeable['legend_background'] = anchored_box
315319
ax = plot.axs[0]
316320
ax.add_artist(anchored_box)
@@ -387,14 +391,25 @@ def add_labels_and_title(plot):
387391
xlabel = plot.labels.get('x', '')
388392
ylabel = plot.labels.get('y', '')
389393
title = plot.labels.get('title', '')
394+
center = 0.5
395+
396+
# This is finicky. Should be changed when MPL
397+
# finally has a constraint based layout manager.
398+
xtitle_y = 0.08
399+
ytitle_x = 0.09
400+
title_y = 0.92
401+
if isinstance(plot.facet, facet_wrap):
402+
title_y += 0.025 * len(plot.facet.vars)
403+
elif isinstance(plot.facet, facet_grid):
404+
title_y += 0.04 * len(plot.facet.cols)
390405

391406
d = dict(
392-
axis_title_x=fig.text(0.5, 0.08, xlabel,
407+
axis_title_x=fig.text(center, xtitle_y, xlabel,
393408
ha='center', va='top'),
394-
axis_title_y=fig.text(0.09, 0.5, ylabel,
409+
axis_title_y=fig.text(ytitle_x, center, ylabel,
395410
ha='right', va='center',
396411
rotation='vertical'),
397-
plot_title=fig.text(0.5, 0.92, title,
412+
plot_title=fig.text(center, title_y, title,
398413
ha='center', va='bottom'))
399414

400415
fig._themeable.update(d)

0 commit comments

Comments
 (0)