gpt4 book ai didi

matplotlib - Jupyter notebook-如何缩放绘图以填充整个页面宽度? (同时保持纵横比)

转载 作者:行者123 更新时间:2023-12-04 12:51:56 45 4
gpt4 key购买 nike

我有一个带有图表的 Jupyter/IPython 笔记本。

我使用以下代码来显示图形,同时保持纵横比为正方形,因此图形不会失真。

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()

关于matplotlib - Jupyter notebook-如何缩放绘图以填充整个页面宽度? (同时保持纵横比),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43749384/

45 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com