【发布时间】:2017-10-11 04:35:09
【问题描述】:
我已经开始更多地使用图形和轴,乍一看,它似乎非常好:可以独立创建和操作轴对象(通过向其添加绘图或更改比例/等),但是我遇到的问题是“Figure”似乎是唯一可以控制轴对象布局的类。
我想做这样的事情:
def plot_side_by_side(lefts, rights, coupled=True, width_ratios=[2,1]):
import matplotlib.gridspec as gridspec
# lefts and rights are lists of functions that
# take axes objects as keywords, the length of this
# object is the number of subplots we have:
plots = list(zip(lefts, rights))
y_size = len(plots)
# create figure with a number of subplots:
fig = plt.figure(figsize=(10,y_size * 4))
gs = gridspec.GridSpec(y_size,2,width_ratios=width_ratios,height_ratios=[1 for _ in plots])
#get axes on the left
cleft_axes = [plt.subplot(gs[0,0])]
if y_size > 1:
cleft_axes += [plt.subplot(gs[i,0], sharex=cleft_axes[0]) for i in range(1,y_size)]
[plt.setp(ax.get_xticklabels(), visible=False) for ax in cleft_axes[:-1]]
# get axes on the right, if coupled we fix the yaxes
# together, otherwise we don't
if coupled:
yaxes = cleft_axes
else:
yaxes = [None for _ in cleft_axes]
cright_axes = [plt.subplot(gs[0,1], sharey=yaxes[0])]
if y_size > 1:
cright_axes += [plt.subplot(gs[i,1], sharey=yaxes[i], sharex=cright_axes[0]) for i in range(1,y_size)]
[plt.setp(ax.get_xticklabels(), visible=False) for ax in cright_axes[:-1]]
# for each plot in our list, give it an axes object if it is on
# the left or right. Now this function will plot on that axes
for (pl, pr), l, r, name in zip(plots,cleft_axes,cright_axes,names):
pl(ax=l)
pr(ax=r)
return fig
我希望能够创建一个函数,该函数将轴对象作为关键字并在其上放置两个图:
def twoplots(ax=ax):
# make a grid of axes, allow them to be plotted to, etc.
# this is all within the space given me by `ax`.
这可能吗?我将如何去做这样的事情?我知道我可以从传递的轴对象中获取图形,是否可以修改父网格规范而不弄乱其他所有网格规范?
【问题讨论】:
-
我已经了解您的目标了。 this question 对你有帮助吗?
-
@ImportanceOfBeingErnest:是的,确实……有点。无论如何从子图轴对象中获取子图轴对象的网格规范?我知道该图是轴对象中的成员指针,但我不知道gridspec。
-
我认为您无法从轴对象中获取 GridSpec 实例。 (不存在
ax.get_gridspec()之类的东西。)但是,您可以使用ax.get_position()获得该职位。由于我仍然对您的目标感到迷茫,因此恐怕我无法为您提供更多帮助。
标签: python python-3.x matplotlib