python 如何使用matplotlib在y轴上绘制等间距的值

r55awzrz  于 2023-01-24  发布在  Python
关注(0)|答案(1)|浏览(136)

我试图在matlplotlib中绘制音高,同时用音符名称标记y轴频率,但在y轴中均匀间隔值时遇到了麻烦。
下面是一个代码示例:

import matplotlib.pyplot as plt
import numpy as np

note_frequency = []
for i in range(60):
    note_frequency.append(
        55 * 2**(i/12)
    )

note_name = [
    'A1', 'A#1', 'B1', 'C2', 'C#2', 'D2', 'D#2', 'E2', 'F2', 'F#2', 'G2', 'G#2',
    'A2', 'A#2', 'B2', 'C3', 'C#3', 'D3', 'D#3', 'E3', 'F3', 'F#3', 'G3', 'G#3',
    'A3', 'A#3', 'B3', 'C4', 'C#4', 'D4', 'D#4', 'E4', 'F4', 'F#4', 'G4', 'G#4',
    'A4', 'A#4', 'B4', 'C5', 'C#5', 'D5', 'D#5', 'E5', 'F5', 'F#5', 'G5', 'G#5',
    'A5', 'A#5', 'B5', 'C6', 'C#6', 'D6', 'D#6', 'E6', 'F6', 'F#6', 'G6', 'G#6',
]

a = np.arange(60)
test_data = [120, 500, 120, 440, 860, 550, 80, 160, 250, 300, 600, 589, 456, 151, 987, 1600]

fig, ax = plt.subplots()

ax.yaxis.set_ticks(note_frequency)
ax.yaxis.set_ticklabels(note_name)
ax.plot(test_data)
plt.show()

绘制问题示例。

qni6mghb

qni6mghb1#

您需要使用这些值的对数:

ax.yaxis.set_ticks(np.log2(note_frequency), note_name)
ax.plot(np.log2(test_data))

或者:

ax.set_yscale('log')
ax.yaxis.set_ticks(note_frequency, note_name)
ax.plot(test_data)

或者:

ax.semilogy(test_data,base=2)
ax.yaxis.set_ticks(note_frequency, note_name)

(谢谢@wwmi)
输出:

相关问题