Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to make local titles using subplot2grid in Python

I'm using suplot2grid like in the example in the matplotlib page:

ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))
plt.suptitle("subplot2grid")

enter image description here

Is there a way to make a local subtitle below ax1, instead of the global one on top of it?

Thanks

like image 263
Leon palafox Avatar asked Jul 25 '13 15:07

Leon palafox


People also ask

How do I create a subplot grid?

There is no built-in option to create inter-subplot grids. In this case I'd say an easy option is to create a third axes in the background with the same grid in x direction, such that the gridline can be seen in between the two subplots.

How do you give titles to each subplot?

If you use Matlab-like style in the interactive plotting, then you could use plt. gca() to get the reference of the current axes of the subplot and combine title. set_text() method to set title to the subplots in Matplotlib.

How do you make multiple subplots in Python?

To create multiple plots use matplotlib. pyplot. subplots method which returns the figure along with Axes object or array of Axes object. nrows, ncols attributes of subplots() method determine the number of rows and columns of the subplot grid.


1 Answers

You can add titles to each sub plot using the set_title() method of the axes. Each title will still be display above the axis. If you want text below the axis, you could use set_xlabel. For example:

import pylab as plt
ax1 = plt.subplot2grid((3,3), (0,0), colspan=3)
ax2 = plt.subplot2grid((3,3), (1,0), colspan=2)
ax3 = plt.subplot2grid((3,3), (1, 2), rowspan=2)
ax4 = plt.subplot2grid((3,3), (2, 0))
ax5 = plt.subplot2grid((3,3), (2, 1))

# add titles to subplots
ax2.set_title('plot 2')
ax3.set_title('plot 3')

# add x-label to subplot
ax1.set_xlabel('plot 1 x-label')

# add y-label to subplot
ax1.set_ylabel('y-label')

plt.tight_layout()
plt.show()

enter image description here

You can also use figtext to add a new title like this:

# add Text
pos = ax1.get_position()
x = pos.x0 + 0.35
y = pos.y0
plt.figtext(x,y,'new title')
plt.tight_layout()
plt.show()
like image 110
Molly Avatar answered Sep 28 '22 10:09

Molly