Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

python - matplotlib figure without whitespace around plot

I know this is a popular question, but couldn't find out any solution that solved my problem so far. I want to build a figure that maps 1:1 from a numpy array.

With this example:

import numpy as np
import matplotlib.pyplot as plt

my_dpi=100
i = np.full((100, 100, 3), 0.5, dtype=np.double)
plt.tight_layout()
fig, ax = plt.subplots(figsize=(100/my_dpi,100/my_dpi), facecolor='red', dpi=my_dpi)
ax.imshow(i)
ax.axis('off')
plt.show()

the best I can get is:

enter image description here

How can I make sure that the boundaries of the subplot (numpy array) extend to the full extent of the containing figure ?

question from:https://stackoverflow.com/questions/65892672/matplotlib-figure-without-whitespace-around-plot

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The easiest way IMHO is actually using package Pillow to export the data. The minimum example would be,

import numpy as np
from PIL import Image

i = np.full((100, 100, 3), 0.5, dtype=np.double)
im = Image.fromarray(i, mode='RGB')
im.save("img.png")

In the case of using matplotlib, you may want to try this method, subplots_adjust. Example:

import numpy as np
import matplotlib.pyplot as plt

my_dpi=100
i = np.full((100, 100, 3), 0.5, dtype=np.double)
fig, ax = plt.subplots(
    figsize=(100/my_dpi,100/my_dpi),
    facecolor='red', dpi=my_dpi
)
ax.imshow(i)
ax.axis('off')
plt.subplots_adjust(0, 0, 1, 1)
plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...