如何确保数字适合所有添加到轴的艺术家?

时间:2017-07-16 12:22:35

标签: matplotlib

考虑以下玩具代码:

# -*- 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)

运行时,会产生如下输出: enter image description here

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

1 个答案:

答案 0 :(得分:2)

你可以创造一个更高的"图和手动设置轴位置,以留出足够的空间。如果要保存图形,请使用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')

enter image description here

不起作用的东西

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

  

仅考虑ticklabels,轴标签和标题。因此,其他   艺术家可能被剪裁。

您会发现,在您的示例代码中,没有轴标签或xticklabels,轴被炸毁,基本上填满了整个图形窗口,圆圈被完全推出。