我有一個圖形的Jupyter/IPython筆記本。Jupyter筆記本 - 如何縮放填充整個頁面寬度的情節? (同時保留長寬比)
我正在使用下面的代碼來顯示圖形,同時保持寬高比平方,因此圖形不會變形。
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.set_aspect('equal')
ax.plot(x,y)
這可以工作,但我想縮放圖形,使其寬度佔據筆記本頁面的整個寬度。我怎樣才能做到這一點?
我有一個圖形的Jupyter/IPython筆記本。Jupyter筆記本 - 如何縮放填充整個頁面寬度的情節? (同時保留長寬比)
我正在使用下面的代碼來顯示圖形,同時保持寬高比平方,因此圖形不會變形。
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()
一件事是設置裏面plt.figure DPI = 200()。這樣會縮放圖形,並且不會超過筆記本的最大尺寸,因此將其設置爲較大的數字會生成寬度不變的圖形。 – 888