gpt4 book ai didi

python - Matplotlib 轴 : splitting an axes object into two

转载 作者:行者123 更新时间:2023-12-04 17:52:00 26 4
gpt4 key购买 nike

我已经开始更多地使用图形和坐标轴,乍一看它似乎非常好:可以独立创建和操作坐标轴对象(通过向其添加绘图或更改比例等),但是我遇到的问题是“图”似乎是唯一可以控制轴对象布局的类。

我想做这样的事情:

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`.

这可能吗?我将如何去做这样的事情?我知道我可以从传递的轴对象中获取图形,是否可以修改父网格规范而不弄乱所有其他网格规范?

最佳答案

希望我在恢复这么旧的线程时没有犯规。我想就我认为 OP 正在尝试做的事情提供一些额外的背景信息。 (至少我希望这是他正在尝试做的事情,因为我正在尝试做同样的事情。)

假设我有一个由 K 个不同类型的子模型组成的统计模型。我想让子模型自己绘制。大多数时候,在典型情况下,每个子模型都会将自己绘制在一个轴对象上。有时,子模型可能需要多个轴来绘制自身。

例如:假设一个模型是一个时间序列模型,子模型显示趋势、季节性、回归效应、假期效应等。如果季节性效应显示年度季节性,它会像趋势模型一样绘制自己(它的效果与时间)。但是,如果它显示星期几的季节性,则情节与时间的关系将无效,因为线条摆动得太快了。绘制星期一的时间序列,然后是星期二的时间序列等会更有效。为了适应更大的方案,您希望这 7 个图的集群成为“季节性图”。

有了 K 个子模型,您通常可以从fig, ax = plt.submodels(K) 然后将 ax[k] 作为 model.submodel[k].plot(ax[k ])。问题是当您想在 ax[k] 上绘制上述星期几的季节性影响时该怎么做。

一个答案可能是“不要使用这种机制:使用 GridSpec 或其他东西”。但我认为这就是问题所在。

关于python - Matplotlib 轴 : splitting an axes object into two,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43927863/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com