Andrew
Andrew

Reputation: 135

How do I set the aspect ratio for a plot in Python with Spyder?

I'm brand new to Python, I just switched from Matlab. The distro is Anaconda 2.1.0 and I'm using the Spyder IDE that came with it.

I'm trying to make a scatter plot with equal ratios on the x and y axes, so that this code prints a square figure with the vertices of a regular hexagon plotted inside.

import numpy
import cmath
import matplotlib

coeff = [1,0,0,0,0,0,-1]
x = numpy.roots(coeff)

zeroplot = plot(real(x),imag(x), 'ro')
plt.gca(aspect='equal')
plt.show()

But plt.gca(aspect='equal') returns a blank figure with axes [0,1,0,1], and plt.show() returns nothing.

Upvotes: 3

Views: 5228

Answers (1)

Marius
Marius

Reputation: 60060

I think the main problem is that plt.gca(aspect='equal') doesn't just grab the current axis and set its aspect ratio. From the documentation, (help(plt.gca)) it appears to create a new axis if the current one doesn't have the correct aspect ratio, so the immediate fix for this should be to replace plt.gca(aspect='equal') with:

ax = plt.gca()
ax.set_aspect('equal')

I should also mention that I had a little bit of trouble getting your code running because you're using pylab to automatically load numpy and matplotlib functions: I had to change my version to:

import numpy
import cmath
from matplotlib import pyplot as plt

coeff = [1,0,0,0,0,0,-1]
x = numpy.roots(coeff)

zeroplot = plt.plot(numpy.real(x), numpy.imag(x), 'ro')
ax = plt.gca()
ax.set_aspect('equal')
plt.show()

People who are already comfortable with Python don't generally use Pylab, from my experience. In future you might find it hard to get help on things if people don't realise that you're using Pylab or aren't familiar with how it works. I'd recommend disabling it and trying to get used to accessing the functions you need through their respective modules (e.g. using numpy.real instead of just real)

Upvotes: 3

Related Questions