3

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

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you. But how do I do the same for say i=[0,1] and j=[0,1,2] using a forloop?
One minute I will update my answer with possible for loop logic.
@gogo answer has been updated to follow your for loop structure
Was testing it out with my case. It Works :)
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

1 Comment

I do not want to fill the space. I just want the graph as such to be repositioned. Any thoughts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.