I have simple code to create a figure with 7 axes/ custom subplots (my understanding is that subplots are equal-sized and equal-spaced and in my particular situation I need one to be larger than the rest).
我有一个简单的代码来创建一个带有7个轴/自定义子图的图形(我的理解是子图是相等大小和等间距的,在我的特定情况下,我需要一个比其余的大一些)。
fig = plt.figure(figsize = (16,12))
# row 1
ax1 = plt.axes([0.1,0.7,0.2,0.2])
ax2 = plt.axes([0.4,0.7,0.2,0.2])
ax3 = plt.axes([0.7,0.7,0.2,0.2])
# big row 2
ax4 = plt.axes([0.1, 0.4, 0.5, 0.2])
#row 3
ax5 = plt.axes([0.1,0.1,0.2,0.2])
ax6 = plt.axes([0.4,0.1,0.2,0.2])
ax7 = plt.axes([0.7,0.1,0.2,0.2])
my question is, how do i get all of these axes to share the same y-axis. All i can find on google/stack is for subplots, eg:
我的问题是,如何让所有这些轴共享相同的y轴。我在谷歌/堆栈上找到的所有内容都是针对子图,例如:
ax = plt.subplot(blah, sharey=True)
but calling the same thing for axes creation does not work:
但是为轴创建调用相同的东西不起作用:
ax = plt.axes([blah], sharey=True) # throws error
is there anyway to accomplish this? What I'm working with is:
无论如何要完成这个?我正在做的是:
1 个解决方案
#1
2
This is quite simple using matplotlib.gridspec.GridSpec
使用matplotlib.gridspec.GridSpec非常简单
gs=GridSpec(3,3)
creates a 3x3 grid to place subplots on
gs = GridSpec(3,3)创建一个3x3网格以放置子图
For your top and bottom rows, we just need to index one cell on that 3x3 grid (e.g. gs[0,0]
is on the top left).
对于您的顶行和底行,我们只需要在该3x3网格上索引一个单元格(例如,gs [0,0]位于左上角)。
For the middle row, you need to span two columns, so we use gs[1,0:2]
对于中间行,您需要跨越两列,因此我们使用gs [1,0:2]
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig=plt.figure(figsize=(16,12))
gs = GridSpec(3,3)
# Top row
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1],sharey=ax1)
ax3=fig.add_subplot(gs[0,2],sharey=ax1)
# Middle row
ax4=fig.add_subplot(gs[1,0:2],sharey=ax1)
# Bottom row
ax5=fig.add_subplot(gs[2,0],sharey=ax1)
ax6=fig.add_subplot(gs[2,1],sharey=ax1)
ax7=fig.add_subplot(gs[2,2],sharey=ax1)
ax1.set_ylim(-15,10)
plt.show()
#1
2
This is quite simple using matplotlib.gridspec.GridSpec
使用matplotlib.gridspec.GridSpec非常简单
gs=GridSpec(3,3)
creates a 3x3 grid to place subplots on
gs = GridSpec(3,3)创建一个3x3网格以放置子图
For your top and bottom rows, we just need to index one cell on that 3x3 grid (e.g. gs[0,0]
is on the top left).
对于您的顶行和底行,我们只需要在该3x3网格上索引一个单元格(例如,gs [0,0]位于左上角)。
For the middle row, you need to span two columns, so we use gs[1,0:2]
对于中间行,您需要跨越两列,因此我们使用gs [1,0:2]
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
fig=plt.figure(figsize=(16,12))
gs = GridSpec(3,3)
# Top row
ax1=fig.add_subplot(gs[0,0])
ax2=fig.add_subplot(gs[0,1],sharey=ax1)
ax3=fig.add_subplot(gs[0,2],sharey=ax1)
# Middle row
ax4=fig.add_subplot(gs[1,0:2],sharey=ax1)
# Bottom row
ax5=fig.add_subplot(gs[2,0],sharey=ax1)
ax6=fig.add_subplot(gs[2,1],sharey=ax1)
ax7=fig.add_subplot(gs[2,2],sharey=ax1)
ax1.set_ylim(-15,10)
plt.show()