在Python中,如何使用matplotlib保存正方形图像?

3
我的目标是创建一系列的matplotlib图表,然后将它们排列在一个大数组中。为此,我需要确保matplotlib图表的输出图像是方形的。如何实现呢?
这是我的代码片段:
figure = matplotlib.pyplot.figure()
figure.suptitle(label, fontsize = 20)
#figure.set_size_inches(19.7, 19.7)
matplotlib.pyplot.scatter(
    variable_1_values,
    variable_2_values,
    s          = marker_size,
    c          = "#000000",
    edgecolors = "none",
    label      = label,
)
matplotlib.pyplot.xlabel(label_x)
matplotlib.pyplot.ylabel(label_y)
legend = matplotlib.pyplot.legend(
    loc            = "center left",
    bbox_to_anchor = (1, 0.5),
    fontsize       = 10
)
print("save {filename}".format(filename = filename))
matplotlib.pyplot.savefig(
    filename,
    bbox_extra_artists = (legend,),
    bbox_inches        = "tight",
    dpi                = 700
)

我知道如何将图形设置为正方形,我需要的是将输出图像设置为正方形。这在概念上就像是取默认输出图像,然后根据需要扩展其背景以使图像成为正方形。

1
不要使用 bbox_inches='tight',该选项会将保存的图形缩小到图形中艺术家的边界框。 - tacaswell
@tcaswell 嘿,谢谢你的建议。我已经尝试了一下,它似乎确实有所帮助(图像似乎与设置为图形的纵横比相匹配),但是我遇到了一个问题,就是坐标轴标签超出了图像边界(http://i.imgur.com/Obw8Hfg.png)。你有什么想法来解决这个问题吗?我正在处理大量的图像,所以我不能单独更改坐标轴数字的格式。 - d3pd
figure.tight_layout()(重新排列/调整轴) - tacaswell
1个回答

3

不确定这是否是您要寻找的,但它能为我生成一个600x600像素的png图像。

import numpy as np
import matplotlib.pyplot as plt

a = np.random.normal(size=1000)
b = np.random.normal(size=1000)

fig = plt.figure(figsize=(6,6))

plt.plot(a,b,'g.')
plt.xlabel("x axis label")
plt.ylabel("y axis label")
plt.title("Random numbers in a scatter plot")

fig.savefig("test.png")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接