matplotlib - 保持蜱位置均匀但值不均匀

时间:2017-09-10 07:24:18

标签: matplotlib

在matplotlib中是否有任何方法可以均匀地保持刻度位置,同时保持其值不均匀,以便数据可以挤压一些间隔并可能在另一个间隔处扩展。 例如,下面的代码生成带有ticks [0.0,0.5,1.0,1.5,2.0]

的正弦波
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt.autoscale(False)
ax.xaxis.set_ticks([0.0,0.5,1.0,1.5,2.0])
plt.show()

我想在ax.xaxis.set_ticks([0.0,0.5,1.0,1.5,2.0])将值0.5更改为0.25,但请将其保存在图上的相同位置。

2 个答案:

答案 0 :(得分:0)

显然以下不是OP所要求的。我将把它留在这里,直到问题被编辑,这样人们至少可以理解不想要的东西

您可以添加set_ticklabels以不同方式标记刻度。

ax.xaxis.set_ticks(     [0.0, 0.50, 1.0,1.5,2.0])
ax.xaxis.set_ticklabels([0.0, 0.25, 1.0,1.5,2.0])

Comlpete示例:

import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2*np.pi*t)
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
ax = plt.gca()
ax.get_xaxis().get_major_formatter().set_useOffset(False)
plt.autoscale(False)
ax.xaxis.set_ticks([0.0,0.5,1.0,1.5,2.0])
ax.xaxis.set_ticklabels([0.0,0.25,1.0,1.5,2.0])
plt.show()

enter image description here

答案 1 :(得分:0)

我正在使用类似的东西。

我认为您想要做的是以下事情:

ax.set_xticks((0,0.25,1,1.5,2)) # makes ticks values uneven
ax.xaxis.set_minor_locator(plt.MultipleLocator(0.25)) # locates ticks at a multiple of the number you provide, as here 0.25 (keeps ticks evenly spaced)