繁体   English   中英

使用matplotlib / pyplot绘制图形并仅保存图形(居中,长宽比相同且没有轴或边框)

[英]Plot something with matplotlib/pyplot and save the plot only (centered, with equal aspect ratio and without axes or borders)

我只想将生成的绘图图像保存到文件中,并编写以下MCVE:

import matplotlib.pyplot as plt

plt.rcParams["axes.facecolor"] = "red"
plt.rcParams["savefig.facecolor"] = "red"
plt.rcParams["savefig.bbox"] = "tight"
plt.rcParams["savefig.pad_inches"] = 0

plt.plot([0, 1], [0, 0], "b-", linewidth="10")
plt.plot([1, 1], [0, 1], "b-", linewidth="10")
plt.plot([1, 0], [1, 1], "b-", linewidth="10")
plt.plot([0, 0], [1, 0], "b-", linewidth="10")

#plt.axis("equal")
#plt.axis("off")
plt.savefig("test.png")

1


plt.axis("equal")
#plt.axis("off")

3


#plt.axis("equal")
plt.axis("off")

2


plt.axis("equal")
plt.axis("off")

4


我发现了有关bboxpad_inches 但是,它仍然不完美。 轴似乎是隐藏的,不是完全关闭的-因此图不会居中。 另外,我想我什至需要轴设置相等的比例,否则矩形将不是正方形?

我想要的是

五

要么

6

您可以定义一个正方形的图形,并使用tight_layout()使填充自动紧凑。

import matplotlib.pyplot as plt

# Creates a figure object of size 6x6 inches
fig = plt.figure(figsize=(6,6))

plt.rcParams["axes.facecolor"] = "red"
plt.rcParams["savefig.facecolor"] = "red"
plt.rcParams["savefig.bbox"] = "tight"
plt.rcParams["savefig.pad_inches"] = 0

plt.plot([0, 1], [0, 0], "b-", linewidth="10")
plt.plot([1, 1], [0, 1], "b-", linewidth="10")
plt.plot([1, 0], [1, 1], "b-", linewidth="10")
plt.plot([0, 0], [1, 0], "b-", linewidth="10")

plt.axis("equal")
plt.axis("off")
fig.tight_layout()
fig.savefig("test.png")

plt.rcParams["savefig.bbox"] = "tight"自动调整图形周围的填充。 这似乎是不希望的。 plt.subplots_adjust(0,0,1,1)这一点并创建没有边距的方形图形( plt.subplots_adjust(0,0,1,1) )将允许轴占据图形中的所有空间。 这样就无需再专门设置方面了,但是当然对于可能仍然有意义的不同情况。

import matplotlib.pyplot as plt

plt.rcParams["axes.facecolor"] = "red"
plt.rcParams["savefig.facecolor"] = "red"

plt.figure(figsize=(4,4))
plt.subplots_adjust(0,0,1,1)
plt.plot([0, 1, 1, 0,0], [0, 0,1,1,0], "b-", linewidth="10", solid_joinstyle="miter")

#plt.gca().set_aspect("equal",adjustable="box" ) # <- not needed
plt.axis("off")
plt.savefig("test.png")
plt.show()

在此处输入图片说明

要获得没有红色边框的图形,可以将数据边距设置为0%( plt.margins(0) ); 但是,由于该行是半切线,因此将其线宽加倍以获得相同的蓝色边框是有意义的。

import matplotlib.pyplot as plt

plt.rcParams["axes.facecolor"] = "red"
plt.rcParams["savefig.facecolor"] = "red"

plt.figure(figsize=(4,4))
plt.subplots_adjust(0,0,1,1)
plt.plot([0, 1, 1, 0,0], [0, 0,1,1,0], "b-", linewidth=20, solid_joinstyle="miter")

#plt.gca().set_aspect("equal",adjustable="box" ) # <- not needed
plt.axis("off")
plt.margins(0.0)
plt.savefig("test.png")
plt.show()

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM