轴类 - 以给定单位明确设置轴的尺寸(宽度/高度)

问题描述 投票:5回答:3

我想用matplotlib创建一个图形,我可以明确指定轴的大小,即我想设置轴bbox的宽度和高度。

我到处都看了,我找不到解决方案。我通常会发现如何调整整个图形的大小(包括刻度和标签),例如使用fig, ax = plt.subplots(figsize=(w, h))

这对我来说非常重要,因为我希望轴的比例为1:1,即纸中的1个单位实际上等于1个单位。例如,如果xrange为0到10,主刻度= 1且x轴为10cm,则1主刻度= 1cm。我将这个数字保存为pdf,将其导入乳胶文档。

This question提出了类似的话题,但答案并没有解决我的问题(使用plt.gca().set_aspect('equal', adjustable='box')代码)

从其他question我看到有可能获得轴大小,但不是如何明确地修改它们。

任何想法我如何设置轴盒大小而不仅仅是图形大小。图形尺寸应适应轴尺寸。

谢谢!

对于那些熟悉乳胶中的pgfplots的人来说,它希望有类似于scale only axis选项的东西(例如参见here)。

python matplotlib plot axis axes
3个回答
15
投票

轴尺寸由图形尺寸和图形间距决定,可以使用figure.subplots_adjust()设置。相反,这意味着您可以通过设置数字大小设置轴大小来计算数字间距:

import matplotlib.pyplot as plt

def set_size(w,h, ax=None):
    """ w, h: width, height in inches """
    if not ax: ax=plt.gca()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom
    figw = float(w)/(r-l)
    figh = float(h)/(t-b)
    ax.figure.set_size_inches(figw, figh)

fig, ax=plt.subplots()

ax.plot([1,3,2])

set_size(5,5)

plt.show()

2
投票

似乎Matplotlib有辅助类,允许您定义具有固定大小Demo fixed size axes的轴


0
投票

我发现ImportanceofBeingErnests回答修改了这个数字大小以调整轴大小提供了不一致的结果与我用来生成发布就绪图的特定matplotlib设置。最终的数字大小存在轻微的错误,我无法找到用他的方法解决问题的方法。对于大多数用例,我认为这不是问题,但是当组合多个pdf用于发布时,错误是显而易见的。

代替开发一个最小的工作示例来找到我正在使用图形调整大小方法的实际问题,我找到了一个工作,使用固定轴大小利用分频器类。

from mpl_toolkits.axes_grid1 import Divider, Size
def fix_axes_size_incm(axew, axeh):
    axew = axew/2.54
    axeh = axeh/2.54

    #lets use the tight layout function to get a good padding size for our axes labels.
    fig = plt.gcf()
    ax = plt.gca()
    fig.tight_layout()
    #obtain the current ratio values for padding and fix size
    oldw, oldh = fig.get_size_inches()
    l = ax.figure.subplotpars.left
    r = ax.figure.subplotpars.right
    t = ax.figure.subplotpars.top
    b = ax.figure.subplotpars.bottom

    #work out what the new  ratio values for padding are, and the new fig size.
    neww = axew+oldw*(1-r+l)
    newh = axeh+oldh*(1-t+b)
    newr = r*oldw/neww
    newl = l*oldw/neww
    newt = t*oldh/newh
    newb = b*oldh/newh

    #right(top) padding, fixed axes size, left(bottom) pading
    hori = [Size.Scaled(newr), Size.Fixed(axew), Size.Scaled(newl)]
    vert = [Size.Scaled(newt), Size.Fixed(axeh), Size.Scaled(newb)]

    divider = Divider(fig, (0.0, 0.0, 1., 1.), hori, vert, aspect=False)
    # the width and height of the rectangle is ignored.

    ax.set_axes_locator(divider.new_locator(nx=1, ny=1))

    #we need to resize the figure now, as we have may have made our axes bigger than in.
    fig.set_size_inches(neww,newh)

值得注意的事情:

  • 一旦在轴实例上调用set_axes_locator(),就会破坏tight_layout()函数。
  • 您选择的原始图形尺寸将是无关紧要的,最终图形尺寸由您选择的轴尺寸和标签/刻度标签/向外刻度的大小决定。
  • 此方法不适用于色标条。
  • 这是我的第一个堆栈溢出帖子。
© www.soinside.com 2019 - 2024. All rights reserved.