Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

python - Why does matplotlib require setting log scale before plt.scatter() but not plt.plot()?

I found out in this helpful answer that plt.scatter() and plt.plot() behave differently when a logrithmic scale is used on the y axis.

With plot, I can change to log any time before I use plt.show(), but log has to be set up-front, before the scatter method is used.

Is this just a historical and irreversible artifact in matplotlib, or is this in the 'unexpected behavior' category?

enter image description here

import matplotlib.pyplot as plt

X = [0.997, 2.643, 0.354, 0.075, 1.0, 0.03, 2.39, 0.364, 0.221, 0.437]
Y = [15.487507, 2.320735, 0.085742, 0.303032, 1.0, 0.025435, 4.436435,
     0.025435, 0.000503, 2.320735]

plt.figure()

plt.subplot(2,2,1)
plt.scatter(X, Y)
plt.xscale('log')
plt.yscale('log')
plt.title('scatter - scale last')   

plt.subplot(2,2,2)
plt.plot(X, Y)
plt.xscale('log')
plt.yscale('log')
plt.title('plot - scale last')   

plt.subplot(2,2,3)
plt.xscale('log')
plt.yscale('log')
plt.scatter(X, Y)
plt.title('scatter - scale first')   


plt.subplot(2,2,4)
plt.xscale('log')
plt.yscale('log')
plt.plot(X, Y)
plt.title('plot - scale first')   


plt.show()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This somehow has to do with the the display area (axes limits) calculated by matplotlib.

This behaviour is fixed by manually editing the axes range by using set_xlim and set_ylim methods.

plt.figure()
plt.scatter(X, Y)
plt.yscale('log')
plt.xscale('log')
axes = plt.gca()
axes.set_xlim([min(X),max(X)])
axes.set_ylim([min(Y),max(Y)])
plt.show()

image

The exact reason of this behavior is however not yet figured out by me. Suggestions are welcomed.

EDIT

As mentioned in comments section, apparently Matplotlib has identified Autoscaling has fundamental problems as a Release Critical Issue on their official Github repo, which would be fixed in upcoming versions. Thanks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...