How to manually position one subplot graph in matplotlib.pyplot

独自空忆成欢 提交于 2019-12-08 08:16:01

问题


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.


回答1:


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:




回答2:


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



来源:https://stackoverflow.com/questions/34799488/how-to-manually-position-one-subplot-graph-in-matplotlib-pyplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!