Matplotlib - 在离散颜色变化的地方准确放置刻度

问题描述

我正在尝试绘制一个使用有限数量的颜色(离散)的颜色条。问题是颜色不会改变主要和次要刻度出现的位置。对数刻度(这是我需要的)的问题更糟,但线性刻度也会发生!

您可以在此处查看示例:

enter image description here

人们可以很容易地注意到颜色在刻度线之前或之后发生了变化。我用 Gimp 打开图像,注释每个刻度线中心像素的水平位置,它们在正确的位置。因此,我确定问题在于绘制彩色矩形。

这是两个颜色条的缩放:

enter image description here

这是生成此图像的代码:

import matplotlib
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
import numpy as np

# fix the seed to reproduce the output exactly
np.random.seed(19680801)

# 2d normal distribution
data = np.random.normal(loc=0,scale=1.,size=(2,1000))
hist = np.histogram2d(data[0,:],data[1,range=[[-4,4],[-3,3]])
x = hist[1]
y = hist[2]
h = hist[0]/np.max(hist[0])

fig,ax = plt.subplots(1,2)

# plot with linear scale
ax[1].set_title('linear scale')
im1 = ax[1].pcolormesh(x,y,h,cmap=plt.get_cmap('jet',5))
cb1 = fig.colorbar(im1,ax=ax[1],orientation='horizontal')
cb1.ax.xaxis.set_major_locator  (mticker.FixedLocator((0,1)))
cb1.ax.xaxis.set_minor_locator  (mticker.FixedLocator((.2,.4,.6,.8)))
cb1.ax.xaxis.set_minor_formatter(mticker.FormatStrFormatter('%.1f'))
cb1.ax.tick_params(axis='x',which='major',length=7)
cb1.ax.tick_params(axis='x',which='minor',length=4,colors='red')

# plot with log scale
ax[0].set_title('log scale')
im0 = ax[0].pcolormesh(x,6),norm=matplotlib.colors.LogNorm(vmin=0.01,vmax=1))
                       
cb0 = fig.colorbar(im0,ax=ax[0],orientation='horizontal')

cb0.ax.xaxis.set_major_locator  (mticker.FixedLocator((.01,.1,1)))
cb0.ax.xaxis.set_minor_locator  (mticker.FixedLocator((.02,.05,.2,.5)))
cb0.ax.xaxis.set_major_formatter(mticker.FormatStrFormatter('%.2f'))
cb0.ax.xaxis.set_minor_formatter(mticker.FormatStrFormatter('%.2f'))
cb0.ax.tick_params(axis='x',length=7)
cb0.ax.tick_params(axis='x',colors='red')

fig.savefig('teste.png',dpi=300)

查看这里的一些旧线程,我可以注意到这个问题在很多年前就已经存在了(请参阅此处第一个响应中的第 5 对勾:Matplotlib discrete colorbar)。

我们该怎么做?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...