2

How do I reposition the graph in the second row such that it is center aligned with respect to the WHOLE figure. On a more general note how to manually reposition the graph anywhere in the same row?

import matplotlib.pyplot as plt
m=0
for i in range(0,2):
    for j in range(0,2):
        if m <= 2:      
            ax = plt.subplot2grid((2,2), (i,j))
            ax.plot(range(0,10),range(0,10))
            m = m+1
plt.show()

Thank you.

enter image description here

gogo
  • 219
  • 4
  • 13

2 Answers2

4

Using GridSpec, you can create a grid of any dimension that can be used for subplot placement.

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

gs = gridspec.GridSpec(4, 4)

ax1 = plt.subplot(gs[:2, :2])
ax1.plot(range(0,10), range(0,10))

ax2 = plt.subplot(gs[:2, 2:])
ax2.plot(range(0,10), range(0,10))

ax3 = plt.subplot(gs[2:4, 1:3])
ax3.plot(range(0,10), range(0,10))

plt.show()

This will create a 4x4 grid, with each subplot taking up a 2x2 sub-grid. This allows you to properly center the bottom subplot.

To use the same same for loop method that you use in your question, you could do the following:

import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt

gs = gridspec.GridSpec(4, 4)
m = 0

for i in range(0, 4, 2):
  for j in range(0, 4, 2):
    if m < 3:
      ax = plt.subplot(gs[i:i+2, j:j+2])
      ax.plot(range(0, 10), range(0, 10))
      m+=1
    else:
      ax = plt.subplot(gs[i:i+2, 1:3])
      ax.plot(range(0, 10), range(0, 10))

plt.show()

The result of both of these code snippets is:

Plots

RyanL
  • 458
  • 3
  • 14
1

What if you have it fill the bottom?

You can use the colspan (or rowspan) to take up multiple parts of a subplot.

import matplotlib.pyplot as plt
m=0
for i in range(0,2):
    for j in range(0,2):
        if m <= 2:
            if m == 2:
                ax = plt.subplot2grid((2,2), (i,j), colspan=2)
            else:
                ax = plt.subplot2grid((2,2), (i,j))
            ax.plot(range(0,10),range(0,10))
            m = m+1
plt.show()

See http://matplotlib.org/users/gridspec.html

  • I do not want to fill the space. I just want the graph as such to be repositioned. Any thoughts? – gogo Jan 14 '16 at 21:45