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

I'm new to Python, I just switched from Matlab. The distribution has Anaconda 2.1.0 and I am 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 this code prints a square shape with the vertices of a regular hexagon built 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 it plt.gca(aspect='equal')

returns an empty figure with axes [0,1,0,1]

and plt.show()

returns nothing.

+3


source to share


1 answer


I think the main problem is plt.gca(aspect='equal')

not just grabbing the current axis and setting its aspect ratio. From the documentation ( help(plt.gca)

) a new axis pops up if the current one doesn't have the correct aspect ratio, so the immediate fix for this should be to replace it plt.gca(aspect='equal')

with:

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

      

I should also mention that I had a bit of trouble getting your code running because you are using pylab

to automatically load functions numpy

and matplotlib

: 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 accustomed to Python usually don't use Pylab in my experience. In the future, you may find it difficult to get help with things if people don't understand that you are using Pylab or are not familiar with how it works. I would recommend turning it off and trying to access the functionality you need through their respective modules (for example, using numpy.real

instead of just real

)

+3


source







All Articles