21

I am trying to overlay a scatter plot onto a contour plot using matplotlib, which contains

 plt.contourf(X, Y, XYprof.T, self.nLevels, extent=extentYPY, \
 origin = 'lower')
 if self.doScatter == True and len(xyScatter['y']) != 0:
 plt.scatter(xyScatter['x'], xyScatter['y'], \
 s=dSize, c=myColor, marker='.', edgecolor='none')
 plt.xlim(-xLimHist, xLimHist)
 plt.ylim(-yLimHist, yLimHist)
 plt.xlabel(r'$x$')
 plt.ylabel(r'$y$')

What ends up happening is the resulting plots extend to include all of the scatter points, which can exceed the limits for the contour plot. Is there any way to get around this?

asked Apr 24, 2012 at 3:03
2
  • 1
    Can you post a complete example that we can try? Commented Apr 24, 2012 at 3:18
  • Can you print the values of xLimHist and yLimHist and show how / where they are calculated? When I make my own contour plot and then overlay scatter points, your code works correctly. If I define xLimHist and yLimHist in such a way that it should exclude some of the scatter points, then the plot does indeed exclude those and it does not fit itself to contain all scatter points. So my guess is that you're defining xLimHist and yLimHist incorrectly. Commented Apr 24, 2012 at 3:27

1 Answer 1

29

I used the following example to try and replicate your problem. If left to default, the range for x and y was -3 to 3. I input the xlim and ylim so the range for both was -2 to 2. It worked.

 import numpy as np
 import matplotlib.pyplot as plt
 from pylab import *
 # the random data
 x = np.random.randn(1000)
 y = np.random.randn(1000)
 fig = plt.figure(1, figsize=(5.5,5.5))
 X, Y = meshgrid(x, y)
 Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
 Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
 Z = 10 * (Z1 - Z2)
 origin = 'lower'
 CS = contourf(x, y, Z, 10, # [-1, -0.1, 0, 0.1],
 cmap=cm.bone,
 origin=origin)
 title('Nonsense')
 xlabel('x-stuff')
 ylabel('y-stuff')
 # the scatter plot:
 axScatter = plt.subplot(111)
 axScatter.scatter(x, y)
 # set axes range
 plt.xlim(-2, 2)
 plt.ylim(-2, 2)
 show()
answered Apr 24, 2012 at 3:45

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.