【问题标题】:How to make sure figure fits all artists added to axes?如何确保图形适合添加到轴的所有艺术家?
【发布时间】:2017-07-16 12:22:35
【问题描述】:

考虑以下玩具代码:

# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

def draw_circle_arrangement(ax, drawing_origin, drawing_space, scale, num_circles, box_height, box_width):
    bw = drawing_space*(box_width*scale)

    drawing_origin[0] = drawing_origin[0] - bw*0.5

    circle_diameter = drawing_space*scale
    circle_radius = 0.5*circle_diameter
    y_delta = np.array([0., circle_diameter])
    x_delta = np.array([circle_diameter, 0.])

    cell_origin = drawing_origin + np.array([circle_radius, circle_radius])
    y_delta_index = 0
    x_delta_index = 0

    for ci in range(num_circles):
        cell_patch = mpatches.Circle(cell_origin + y_delta_index*y_delta + x_delta_index*x_delta, radius=circle_radius, color='k', fill=False, ls='solid', clip_on=False)
        ax.add_artist(cell_patch)

        if y_delta_index == box_height - 1:
            y_delta_index = 0
            x_delta_index += 1
        else:
            y_delta_index += 1


fig, ax = plt.subplots()

# each tuple is: number of circles, height of box containing circles, width of box containing circle
circle_arrangements = [(10, 2, 5), (3, 1, 3), (1, 1, 1)]
data = np.random.rand(3)
ax.set_ylim([0, 1])
ax.plot(np.arange(3) + 1, data, marker='o')
ax.get_xaxis().set_ticklabels([])
scale = 1./10.

for i, ca in enumerate(circle_arrangements):
    do = np.array([1.0 + i, -0.2])
    nc, bh, bw = ca
    draw_circle_arrangement(ax, do, 0.8, scale, nc, bh, bw)

运行时,它会产生如下输出:

如您所见,圆形排列补丁在图的底部被裁剪?如何确保matplotlib 为图中的所有绘图提供了足够的空间?

【问题讨论】:

标签: matplotlib


【解决方案1】:

您可以创建一个“更高”的图形并手动设置轴位置,以便为自己留出足够的空间。当你想保存图形时,使用bbox_inches='tight' 裁剪掉不必要的空白。

# Figure width, height in inches
fig = plt.figure(figsize=(6.4,8))
# [xo,yo,w,h] in normalized fig coords
ax = fig.add_axes([.125,.4,.75,.5])     

circle_arrangements = [(10, 2, 5), (3, 1, 3), (1, 1, 1)]
data = np.random.rand(3)
ax.set_ylim([0, 1])
ax.plot(np.arange(3) + 1, data, marker='o')
ax.get_xaxis().set_ticklabels([])
scale = 1./10.

for i, ca in enumerate(circle_arrangements):
    do = np.array([1.0 + i, -0.2])
    nc, bh, bw = ca
    draw_circle_arrangement(ax, do, 0.8, scale, nc, bh, bw)

plt.savefig('foo.png', bbox_inches='tight')

有些东西不起作用

我本来打算建议 plt.tight_layout() 但这不起作用。 The documentation's first caveat 声明它:

仅考虑刻度标签、轴标签和标题。因此,其他 艺术家可能会被剪辑。

您会发现,在没有轴标签或 xticklabels 的示例代码中,轴被放大以填充整个图形窗口,而圆圈被完全推出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-04
    相关资源
    最近更新 更多