简体   繁体   中英

Matplotlib - pyplot incorrectly setting axes ticks when using scatter()

I am trying to customize the xticks and yticks for my scatterplot with the simple code below:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(1,1,1)

y_ticks = np.arange(10, 41, 10)
x_ticks = np.arange(1000, 5001, 1000)

ax.set_yticks(y_ticks)
ax.set_xticks(x_ticks)

ax.scatter(some_x, some_y)

plt.show()

If we comment out the line: ax.scatter(x, y) , we get an empty plot with the correct result:

在此处输入图片说明

However if the code is run exactly as shown, we get this:

在此处输入图片说明

Finally, if we run the code with ax.set_yticks(yticks) and ax.set_xticks(xticks) commented out, we also get the correct result (just with the axes not in the ranges I desire them to be):

在此处输入图片说明

Note that I am using Python version 2.7. Additionally, some_x and some_y are omitted.

Any input on why the axes are changing in such an odd manner only after I try plotting a scatterplot would be appreciated.

EDIT:

If I run ax.scatter(x, y) before xticks and yticks are set, I get odd results that are slightly different than before:

在此处输入图片说明

Matplotlib axes will always adjust themselves to the content. This is a desirable feature, because it allows to always see the plotted data, no matter if it ranges from -10 to -9 or from 1000 to 10000.

Setting the xticks will only change the tick locations. So if you set the ticks to locations between -10 and -9, but then plot data from 1000 to 10000, you would simply not see any ticks, because they do not lie in the shown range.

If the automatically chosen limits are not what you are looking for, you need to set them manually, using ax.set_xlim() and ax.set_ylim() .

Finally it should be clear that in order to have correct numbers appear on the axes, you need to actually use numbers . If some_x and some_y in ax.scatter(some_x, some_y) are strings, they will not obey to any reasonable limits, but simply be plotted one after the other.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM