在不更改绘图的情况下重新调整y轴的比例

时间:2019-08-28 11:14:04

标签: python python-3.x matplotlib

我有什么

我正在尝试使用python 3创建值的“热图”。
我被困在y刻度之间的间隔上,几个SO问题无法帮助我...

到目前为止,我的代码如下:

data = np.load('path\to\data\datafile.npy')

# plot using imshow (and use interpolation)
plt.imshow(data,
           cmap          = 'RdBu_r', 
           aspect        = 'auto', 
           vmin          = -.4,
           vmax          =  .4,
           origin        = 'lower',
           extent        = [-1000, 4500, 2, 48], 
           interpolation = 'hanning')

# plt parameters
plt.xlim(-750, 4250)
plt.colorbar()
plt.vlines(0, 
           frequencies[0], 
           frequencies[-1], 
           colors = 'black',
           label = 'Stimulus onset',
           linewidth = 2.5)
plt.legend(loc=(1,1.04))
plt.title('Time-frequency using Morlet wavelets\nSubject: {}'.format(SUB_ID))
plt.ylabel('Frequency (in Hz)')
plt.xlabel('Time (in ms)')
plt.show()

这给了我以下情节:

Plot with wrong y-axis scaling

我想要的

y轴上的标签有误。
具体来说,y轴应具有以下标签(以对数形式隔开):

In [15]:
# parameters
min_freq = 2;
max_freq = 48;
num_frex = 20;

# define frequencies of interest
frequencies = np.logspace(np.log10(min_freq), 
                          np.log10(max_freq), 
                          num_frex)
frequencies

Out[15]: 
array([ 2.        ,  2.36413729,  2.79457255,  3.30337659,  3.90481788,
        4.61576277,  5.45614844,  6.44954198,  7.62380134,  9.01185651,
       10.652633  , 12.59214343, 14.8847779 , 17.59482922, 20.7982959 ,
       24.58501342, 29.06117345, 34.35230187, 40.60677887, 48.        ])

生成的图应如下所示(当关注y轴时):

Plot with correct y-label spacing

所以:

  • 不应更改情节
  • y轴标签应从线性转换为对数
  • 标签之间的间距应与后面的图相同

datafile.npy can be found here

1 个答案:

答案 0 :(得分:0)

您只需要为情节提供自定义的ytick列表:

# parameters
min_freq = 2;
max_freq = 48;
num_frex = 20;

# define frequencies of interest
frequencies = np.logspace(np.log10(min_freq), 
                      np.log10(max_freq), 
                      num_frex)

plt.yticks(frequencies)

有关更多信息,请参见https://matplotlib.org/3.1.0/api/_as_gen/matplotlib.pyplot.yticks.html#matplotlib.pyplot.yticks