Chilichiller
Chilichiller

Reputation: 487

matplotlib's scatter plot changes the axis of another plot

I want to combine a contourf() plot and a scatter() plot from matplotlib.pyplot, however, adding the scatter plot changes the axis of the plot. Here a small example:

from matplotlib import pyplot as plt
import numpy as np

data = np.random.rand(10,10)
plt.contourf(data)
# plt.scatter(3, 7, s=200, color='k')
plt.show()

This script creates some plot like the this:

without scatter()

When uncommenting plt.scatter(3, 7, s=200, color='k') the axis limits are changed, resulting in a white frame around the contour plot. A possibility is to manually set the axis limits using plt.xlim and plt.ylim, but it seems an unnecessary hassle. How can I elegantly make this work?

with scatter()

Upvotes: 2

Views: 541

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77941

add

plt.xlim(auto=False)
plt.ylim(auto=False)

right after countorf line; or you may always do

xl, yl = plt.xlim(), plt.ylim()

anywhere in your code that you are happy with x,y limits, and then at the end do

plt.xlim(xl)
plt.ylim(yl)

Upvotes: 5

Related Questions