matplotlib:不均匀间隔的刻度/指定颜色的零点

3 投票
1 回答
2571 浏览
提问于 2025-04-18 08:07

我已经尝试解决一个问题很长时间了,但无论是StackOverflow还是其他网站都没有帮到我。

我想绘制一个范围从-40到36的场(使用contourf),并且希望颜色条使用gist_rainbow_r这个配色方案,分成52个离散的步骤。 如你所见,这些级别并不是均匀分布的。我希望颜色条上的刻度是均匀分布的(所有级别都应该均匀分布),而且颜色是这52种gist_rainbow_r颜色的离散化结果。这可能实现吗?下面是我的代码片段。

    levels = [-40,-30,-20,-15,-12,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
    # define the colormap
    cmap = cm.get_cmap('gist_rainbow_r',52)
    # define the bins and normalize
    norm = mpl.colors.BoundaryNorm(levels, cmap.N)
    contourplot = map.contourf(xpoints,ypoints,fieldtoplot,range(-40,36),cmap=cmap,norm=norm,spacing='regular')

    ax = plt.gca()  # Gets the current axes
    divider = make_axes_locatable(ax)  # Lets us move axes around
    cax = divider.append_axes("bottom", size="2%",pad=-0.02,axes_class=maxes.Axes)  #Adds an axis for the colorbar
    F.add_axes(cax)  # Adds the new axis to the figure as the current working axis
    bar = plt.colorbar(contourplot,cax=cax,orientation='horizontal',spacing='regular',extend='both',extendfrac='auto',extendrect='True',format='%1i',ticks=levels, boundaries=levels) # Plots colorbar in new axis 
    bar.update_ticks()

祝好

马丁

1 个回答

5

其实,解决方案非常简单,写出来有点不好意思……抱歉打扰大家了!

好了,下面是我解决问题的方法:

levels = [-40,-30,-20,-15,-12,-10,-9,-8,-7,-6,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36]
# define the colormap
cmap = cm.get_cmap('gist_rainbow_r',52)
# define the bins and normalize
norm = mpl.colors.BoundaryNorm(levels, cmap.N)
contourplot = map.contourf(xpoints,ypoints,fieldtoplot,range(-40,36),cmap=cmap,norm=norm,spacing='uniform', levels=levels)

ax = plt.gca()  # Gets the current axes
divider = make_axes_locatable(ax)  # Lets us move axes around
cax = divider.append_axes("bottom", size="2%",pad=-0.02,axes_class=maxes.Axes)  #Adds an axis for the colorbar
F.add_axes(cax)  # Adds the new axis to the figure as the current working axis
bar = plt.colorbar(contourplot,cax=cax,orientation='horizontal',spacing='uniform',extend='both',extendfrac='auto',extendrect='True',format='%1i',ticks=levels, boundaries=levels) # Plots colorbar in new axis 
bar.update_ticks()

为了更清楚:把“spacing”设置为“uniform”(而不是“equal”——我在查看colorbar.py时发现根本没有这个设置),然后把“levels”传递给contourf函数。

在这里:感谢@Saullo Castro部分回答了这个问题!

祝好

马丁

撰写回答