matplotlib – Jupyter笔记本 – 如何缩放绘图以填充整个页面宽度? (同时保留纵横比)

我有一个带图形的Jupyter / I
Python笔记本.

我使用以下代码显示图形,同时保持纵横比方形,以便图形不会失真.

fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal')
ax.plot(x,y)

这有效,但我想缩放图形,使其宽度占据笔记本页面的整个宽度.我怎样才能做到这一点?

最佳答案 你需要设置figsize的正确(宽度,高度):

%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np
import sys

# Plot a random line that fill whole width of the cell in jupyter notebook
# need ranges of x, y to get proper (width, height) of figure

x = np.random.randn(5)   # prep data to plot
y = np.random.randn(5)
xmin,xmax = min(x),max(x)
ymin,ymax = min(y),max(y)

yox = None
if (xmax-xmin)!=0:
    yox = (ymax-ymin)/(xmax-xmin)

# set number that should spans cell's width
pwidth = 20    # inches

if yox>1.0:
    # tall figure
    width, height = pwidth, pwidth*yox
elif yox==1.0:
    width, height = pwidth, pwidth
elif yox<1.0:
    # wide figure
    width, height = pwidth*yox, pwidth
    if width<pwidth:
        height = height/width*pwidth
        width = pwidth
else:
    sys.exit

fig = plt.figure(figsize=(width, height))  # specify (width,height) in inches
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal') # preserve aspect ratio
ax.plot( x, y )        # should fill width of notenook cell

plt.show()
点赞