【问题标题】:Matplotlib axes: splitting an axes object into twoMatplotlib 轴:将轴对象分成两个
【发布时间】: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


【解决方案1】:

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

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-08
    • 2021-12-30
    • 2012-12-13
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    相关资源
    最近更新 更多