【问题标题】:Jupyter notebook- how to scale plot to fill entire width of page? (while preserving aspect ratio)Jupyter notebook-如何缩放绘图以填充整个页面宽度? (同时保持纵横比)
【发布时间】:2017-09-30 15:44:26
【问题描述】:

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

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

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

这可行,但我想缩放图表,使其宽度占据笔记本页面的整个宽度。我该怎么做?

【问题讨论】:

  • 对我的目的有用的一件事是在 plt.figure() 中设置 dpi=200。这会放大图表,并且不会大于笔记本的最大尺寸,因此将其设置为较大的数字会生成具有恒定宽度的图表。

标签: matplotlib graph ipython jupyter-notebook


【解决方案1】:

您需要设置正确的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()

【讨论】:

  • 我正在寻找能够保留图形纵横比的东西,并且可以放大到填充笔记本整个宽度所需的大小。不知道图的高度会提前多少。
  • x 和 y 的范围是多少?
  • 你不能用笔记本的整个宽度来绘制,而是单元格。
  • 是的,对不起,我的意思是使用单元格的宽度。
  • 我事先不知道x和y的范围。我希望图表自动缩放,无论它们是什么。
猜你喜欢
  • 1970-01-01
  • 2013-08-07
  • 2011-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多