12

I have a Jupyter/IPython notebook with a graph.

I am using the following code to display the graph, while keeping the aspect ratio square so the graph does not get distorted.

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

This works, but I want to scale the graph so its width takes up the entire width of the notebook page. How can I do this?

1
  • 1
    One thing that works for my purposes is to set dpi=200 inside plt.figure(). This scales the graph up, and it won't get any larger than the maximum size of the notebook, so setting it to some large number produces a graph with a constant width. Commented May 3, 2017 at 5:43

1 Answer 1

1

You need to set proper (width,height) of 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()
Sign up to request clarification or add additional context in comments.

5 Comments

I am looking for something that preserves the aspect ratio of the graph, and scales up to be as big as it needs to be to fill up the entire width of the notebook. I do not know what the height of the graph will be in advance.
What are the ranges of x and y ?
You can't use the whole width of the notebook to plot, but the cell.
Yes, sorry, using the width of the cell is what I mean.
I do not know the ranges of x and y in advance. I want the graph to scale automatically no matter what they are.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.