用log xscale强制负xticks

时间:2019-05-22 16:19:43

标签: python matplotlib

您好,我正在尝试绘制一些以对数标度(base2)演变但有一些负数的数据(它的频率相关,因此与我的中心频率成负数)。我能够完全绘制它,但是刻度标签不正确(即使我必须强制将-0.5设置为正值,以便xscale包含它,也应将其从-0.5改为64)

xData = np.array([10, 20, 40, 80, 160, 320, 640, 1280])

yData1 = np.array([-6.30404, 8.69744, 12.975, 26.69, 18.76, 18.85, 18.91, 22.68])

yData2 = np.array([-7.59254, 10.9645, 21.345, 20.48, 22.34, 25.57, 24.68, 25.52])

yData3 = np.array([2.20636, 1.98, 6.14625, 11.099, 23.41, 23.77,35.6, 33.996,])

yData4 = np.array([-3.19325, 0.8, 4.48, 11.033, 22.18, 23.15, 31.826, 34.755])

yData5 = np.array([0.592, 3.84101, 5.12036, 12.02374, 17.124, 22.88, 26.49, 32.117])

yData6 = np.array([0.516, 5.23039, 7.66303, 11.546, 16.918, 19.15, 24.35, 25.6732])

plt.figure()
plt.plot(xData/20, yData1)
plt.plot(xData/20, yData2)
plt.plot(xData/20, yData3)
plt.plot(xData/20, yData4)
plt.plot(xData/20, yData5)
plt.plot(xData/20, yData6)
plt.grid(True, linestyle='--', which='both')
plt.ylim(-10,40)
plt.xticks([-0.5, 1, 2, 4, 8, 16, 32, 64])
plt.xscale('log', basex=2)
plt.gca().set_xticklabels([0.5, 1, 2, 4, 8, 16, 32, 64])
#plt.legend()
plt.show()

1 个答案:

答案 0 :(得分:0)

我不确定为什么第一个刻度位于默认位置并标记为0.5而不是-0.5,但是您非常接近更改刻度标签。您只需要将-0.5乘0.5即可

plt.xscale('log', basex=2)
plt.xticks([0.5, 1, 2, 4, 8, 16, 32, 64]) # <--- change -0.5 to 0.5
plt.gca().set_xticklabels([-0.5, 1, 2, 4, 8, 16, 32, 64]) # <--- change 0.5 to -0.5

enter image description here