Han Zhengzu
Han Zhengzu

Reputation: 3852

How to draw rectangle outside of the plot frame in Matplotlib

I want to generate the subfigure's title in the style of followed figure:

enter image description here

A gray box should be beneath the title which are at the top of the scatter point.

Here is the code I have tried:

x = random.sample(range(50), 50)
y= random.sample(range(50), 50)

fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.scatter(x,y,label='a')
ax.set_aspect('equal')
ax.set_xlim(0,60)
ax.set_ylim(0,60)
ax.plot([0,60], [0, 60], color='k', linestyle='-', linewidth=1.25)

ax.add_patch(patches.Rectangle((0,60),60, 10,facecolor='silver',linewidth = 0))
TITLE = ax.text(26,61, r'$\mathregular{Title}$',fontsize = 14,zorder = 5,color = 'k')

The result show like:

enter image description here

The rectangle as the background box of title can't be shown in my result

Any advice or better solution are appreciate!

Upvotes: 10

Views: 10804

Answers (2)

heisenBug
heisenBug

Reputation: 965

I think a better way is to use the clip_on=False option for Rectangle:

import random
import matplotlib.pyplot as pyplot

x = random.sample(range(50), 50)
y= random.sample(range(50), 50)

fig = pyplot.figure()
ax = pyplot.subplot(111)
ax.scatter(x,y,label='a')
ax.set_aspect('equal')
ax.set_xlim(0,60)
ax.set_ylim(0,60)
ax.plot([0,60], [0, 60], color='k', linestyle='-', linewidth=1.25)

ax.add_patch(pyplot.Rectangle((0,60),60, 10,facecolor='silver',
                              clip_on=False,linewidth = 0))
TITLE = ax.text(26,61, r'$\mathregular{Title}$',fontsize = 14,zorder = 5,
                color = 'k')
pyplot.show()

This yields a rectangle drawn outside of the axes, without having to resort to extra spaces:

enter image description here

Upvotes: 16

Lucas
Lucas

Reputation: 7341

Remove this line:

ax.add_patch(patches.Rectangle((0,60),60, 10,facecolor='silver',linewidth = 0))

And change the last line by adding bbox:

TITLE = ax.text(26,62, 'Title',fontsize = 14,zorder = 6, color = 'k',
                bbox={'facecolor':'silver', 'alpha':0.5, 'pad':4})

bbox_example

The only way I found to give it an arbitrary length is to add blank spaces.

TITLE = ax.text(1,62, '                     Title                    ',
                fontsize = 14,zorder = 6,color = 'k', 
                bbox={'facecolor':'silver', 'alpha':0.5, 'pad':4})

bbox_example_2

For more info on bbox see this question in SO.

Upvotes: 2

Related Questions