轴类 - 以给定单位明确设置轴的大小(宽度/高度) [英] Axes class - set explicitly size (width/height) of axes in given units

查看:30
本文介绍了轴类 - 以给定单位明确设置轴的大小(宽度/高度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to to create a figure using matplotlib where I can explicitly specify the size of the axes, i.e. I want to set the width and height of the axes bbox.

我已经环顾四周,但找不到解决方案.我通常发现的是如何调整完整图的大小(包括刻度和标签),例如使用 fig, ax = plt.subplots(figsize=(w, h))

I have looked around all over and I cannot find a solution for this. What I typically find is how to adjust the size of the complete Figure (including ticks and labels), for example using fig, ax = plt.subplots(figsize=(w, h))

这对我来说非常重要,因为我希望轴的比例为 1:1,即纸上的 1 个单位等于现实中的 1 个单位.例如,如果 xrange 为 0 到 10,主刻度 = 1,x 轴为 10cm,则 1 个主刻度 = 1cm.我会将此图保存为 pdf 以将其导入到 Latex 文档中.

This is very important for me as I want to have a 1:1 scale of the axes, i.e. 1 unit in paper is equal to 1 unit in reality. For example, if xrange is 0 to 10 with major tick = 1 and x axis is 10cm, then 1 major tick = 1cm. I will save this figure as pdf to import it to a latex document.

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

This question brought up a similar topic but the answer does not solve my problem (using plt.gca().set_aspect('equal', adjustable='box') code)

从另一个问题我看到有可能得到轴大小,但不知道如何显式修改它们.

From this other question I see that it is possible to get the axes size, but not how to modify them explicitly.

任何想法如何设置轴框大小而不仅仅是图形大小.图形大小应适应轴大小.

Any ideas how I can set the axes box size and not just the figure size. The figure size should adapt to the axes size.

谢谢!

对于那些熟悉 pgfplots 在乳胶中的人来说,它会希望有一些类似于 scale 的东西only axis 选项(例如,请参见 此处).

For those familiar with pgfplots in latex, it will like to have something similar to the scale only axis option (see here for example).

推荐答案

轴大小由图形大小和图形间距决定,可以使用 figure.subplots_adjust().相反,这意味着您可以通过设置图形大小来设置轴大小,同时考虑图形间距:

The axes size is determined by the figure size and the figure spacings, which can be set using figure.subplots_adjust(). In reverse this means that you can set the axes size by setting the figure size taking into acount the figure spacings:

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()

这篇关于轴类 - 以给定单位明确设置轴的大小(宽度/高度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆