首页 > 解决方案 > Matplotlib 在大范围内绘制非常小的 X 轴间隔?

问题描述

我的X轴数据是这样的:

 X =[0.0, 0.9, 0.99, 0.999, 0.9999, 0.99999, 0.999999, 0.9999999, 0.99999999, 0.999999999, 0.9999999999, 0.99999999999, 0.999999999999, 0.9999999999999, 0.99999999999999, 1.000000000000001, 1.00000000000001, 1.0000000000001, 1.000000000001, 1.00000000001, 1.0000000001, 1.000000001, 1.00000001, 1.0000001, 1.000001, 1.00001, 1.0001, 1.001, 1.01, 1.1]

我的 Y 轴数据是这样的:

Y = [1.0, 3.16227766016838, 9.999999999999995, 31.622776601683782, 100.00000000000551, 316.22776601755754, 999.9999999856221, 3162.277661000621, 9999.999974876204, 31622.777048860404, 99999.99586298171, 316227.7529344374, 1000011.0610435781, 3161786.1272856337, 10003998.786452563, -30011996.35935769, -10003998.786452563, -3163542.1874750517, -999955.5526723525, -316227.7529344374, -99999.99586298171, -31622.77529344374, -10000.000030387355, -3162.2776592452046, -1000.0000000411333, -316.2277660158021, -100.00000000000551, -31.622776601685537, -9.999999999999995, -3.162277660168378]

我想绘制这些数据,我应该得到一个带有曲线的图表,但我得到的是:

plt.plot(X,Y)
plt.show()

#output:

错误的绘图 - 使用 X 和 Y 数据时的图像

但是当我使用这段代码时:

​plt.plot(range(30),Y)
plt.show()

#Output:

正确的绘图但错误的 X 轴刻度

我如何获得第二个图,但使用上面提到的列表的 X 数据?

标签: pythonmatplotlibplotdata-science

解决方案


所以这是答案:

import matplotlib
from matplotlib.pyplot import figure
figure(num=None, figsize=(18, 16), dpi=80, facecolor='w', edgecolor='k')
plt.plot(range(29), Y, 'o-')
ax = plt.gca()
fmtr = matplotlib.ticker.IndexFormatter(X)
ax.xaxis.set_major_formatter(fmtr)

#Outputs: 

它是如何需要的


推荐阅读