不同值的刻度之间的相等间距

时间:2017-12-11 15:54:28

标签: python matplotlib

我已经调查了thisthis并尝试了那里提到的方法,但我得到的结果与我想要做的完全不同。

这是我的代码:

import numpy as np


import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
from collections import Counter


fig, ax = plt.subplots()

ax.set_title("Right Ear")


x = [125,250,500,750,1000,1500,2000,3000,4000,6000,8000]

ax.set_ylabel("db HL")
ax.set_xlabel("Frequency")
plt.axis([0,9000,130,-10])
ax.set_facecolor("#ffd2d2")
ax.xaxis.set_ticks(x)
ax.xaxis.set_ticklabels(["","","500","","1K","","2K","","4K","","8K"])

ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

ax.plot()
plt.grid(color="grey")
plt.show()

这给出了这个结果: Unequally spaced grid lines

我无法弄清楚如何使xaxis网格线像这样均匀间隔: Equally spaced grid lines

上述链接中给出的方法给出了不同的结果。

2 个答案:

答案 0 :(得分:3)

事实上,它们间隔相等但你用对数间隔绘制它们,你应该使用对数刻度。

import numpy as np


import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
from collections import Counter


fig, ax = plt.subplots()

ax.set_title("Right Ear")


x = [125,250,500,750,1000,1500,2000,3000,4000,6000,8000]

ax.set_ylabel("db HL")
ax.set_xlabel("Frequency")

ax.set_facecolor("#ffd2d2")
ax.set_xscale('log')
ax.set_xlim(120,9000)
ax.set_ylim(130,-10)
ax.xaxis.set_ticks(x)
ax.xaxis.set_ticklabels(["","","500","","1K","","2K","","4K","","8K"])

ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

ax.plot()
plt.grid(color="grey")
plt.show()

enter image description here

答案 1 :(得分:1)

您显示的图表具有对数缩放,基数为2;即每个刻度都是前一刻度的两倍。 要将比例设置为与基数2对数,请使用ax.set_xscale('log', basex=2)

import matplotlib.pyplot as plt

fig, ax = plt.subplots()

ax.set_title("Right Ear")
ax.set_ylabel("db HL")
ax.set_xlabel("Frequency")
ax.set_xlim(100,9000)
ax.set_ylim(130,-10)
ax.set_facecolor("#ffd2d2")

x = [125,250,500,1000,2000,4000,8000]
ticks = [125,250,500,"1K","2K","4K","8K"]
xm = [750,1500,3000,6000]

ax.set_xscale('log', basex=2)
ax.set_xticks(x)
ax.set_xticks(xm, minor=True)
ax.set_xticklabels(ticks)
ax.set_xticklabels([""]*len(xm), minor=True)


ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

ax.plot()
ax.grid(color="grey")
ax.grid(axis="x", which='minor',color="grey", linestyle="--")
plt.show()

enter image description here