matplotlib colorbar tick标签外面的bug

时间:2014-07-28 13:48:37

标签: matplotlib colorbar

当自定义刻度超出vmin或vmax时,自定义标签会移位:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import random

# Make plot with horizontal colorbar
fig, ax = plt.subplots()

data = random((250,250)) + 3.5

norm = matplotlib.colors.Normalize(vmin=2.5,vmax=4.5)

cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot, norm=norm)
ax.set_title('Gaussian noise with horizontal colorbar')

cbar = fig.colorbar(cax, ticks=[1,2,3,4], orientation='horizontal')
cbar.set_ticklabels(['one','two', 'three', 'four'])# horizontal colorbar

plt.savefig("example.png")

enter image description here

enter image description here

这是一个错误吗?任何解决方法?

2 个答案:

答案 0 :(得分:2)

您可以获得第一个实际价格,并将标签与您指定的价格/位置进行比较。然后,您可以使用该索引来启动自定义标签 这是一个修改过的例子:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import random

# Make plot with horizontal colorbar
fig, ax = plt.subplots()

data = random((250,250)) + 3.5

norm = matplotlib.colors.Normalize(vmin=2.5,vmax=4.5)

cax = ax.imshow(data, interpolation='nearest', cmap=cm.afmhot, norm=norm)
ax.set_title('Gaussian noise with horizontal colorbar')

TICKS = [1,2,3,4]

cbar = fig.colorbar(cax, ticks=TICKS, orientation='horizontal')

# the following command extracts the first tick object from the x-axis of
# the colorbar:
tick = cbar.ax.get_xaxis().get_major_ticks()[0]

# Here you compare the text of the first tick label to all the tick locations
# you have defined in TICKS (they need to be strings for this):
CUSTOM_INDEX = [str(S) for S in TICKS].index(tick.label1.get_text())

TICKLABELS = ['one','two', 'three', 'four']

# Now, you can use the index of the actual first tick as a starting tick to
# your list of custom labels:
cbar.set_ticklabels(TICKLABELS[CUSTOM_INDEX:])# horizontal colorbar

plt.show()

new custom labels

答案 1 :(得分:1)

这不是colorbar特有的。如果将刻度标签指定为字符串列表,则它们始终(也在X或Y轴上)分配给第一个刻度。看到这个简单的例子:

import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.set_xticklabels(["one", "two", "three"])

这绘制:

enter image description here

现在,刻度标签onetwothree分别对应0.0,0.2和0.4。

如果我们通过以下方式放大:

ax.set_xlim(.1,.9)

我们得到:

enter image description here

现在相同的标签对应于0.1,0.2,0.3,因为它们是最左边的标签。

因此,标签字符串不会与刻度位置绑定。

有一些解决方法,但最好的解决方法实际上取决于你想要完成的任务。