使用双刻度绘制颜色条

13

我希望能够绘制一个(垂直)的彩条,每侧都有不同的刻度标尺(对应于同一数量的两个不同单位),例如一侧是华氏度,另一侧是摄氏度。显然,我需要分别为每一侧指定刻度。

您有什么好的想法吗?


http://matplotlib.org/examples/api/two_scales.html,你试过这个吗?发一个样本数据。 - Kirubaharan J
1
我正在使用 pcolormesh 绘制二维数据。我的问题特别关注的是颜色条,而不是坐标轴本身。 - andreas-h
是否可以提供样本数据? - Kirubaharan J
https://dev59.com/VmYr5IYBdhLWcg3wTYgQ?rq=1 - Kirubaharan J
1
@andreas-h 彩色条形图存在于坐标轴上(您可以通过“ax”属性访问它),因此您应该能够像与更大的绘图坐标轴一样调整比例。 - Ajean
4个回答

14

那应该能让你开始了:

import matplotlib.pyplot as plt
import numpy as np

# generate random data
x = np.random.randint(0,200,(10,10))
plt.pcolormesh(x)

# create the colorbar
# the aspect of the colorbar is set to 'equal', we have to set it to 'auto',
# otherwise twinx() will do weird stuff.
cbar = plt.colorbar()
pos = cbar.ax.get_position()
cbar.ax.set_aspect('auto')

# create a second axes instance and set the limits you need
ax2 = cbar.ax.twinx()
ax2.set_ylim([-2,1])

# resize the colorbar (otherwise it overlays the plot)
pos.x0 +=0.05
cbar.ax.set_position(pos)
ax2.set_position(pos)

plt.show()

在此输入图片描述


您不需要调整色条的大小,只需将axisbelow设置为False: cbar.ax.set_axisbelow(False) # 1. 轴 ax2 = cbar.ax.twinx() ax2.set_ylim([low,high]) # low high用于限制 ax2.set_axisbelow(False) # 2. 轴 - Andreas
@Andreas 我不明白你的意思: set_axisbelow 对坐标轴实例的大小或位置没有影响。 - hitzg
啊,我明白你的意思了,我以为它是用来偏移第二个轴的 - 所以在你的上下文中忽略它就好了,对于造成的困惑我很抱歉。 - Andreas

12
如果您为色条创建一个子图,您可以为该子图创建一个双轴,并像普通轴一样操作它。
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,2.7)
X,Y = np.meshgrid(x,x)
Z = np.exp(-X**2-Y**2)*.9+0.1

fig, (ax, cax) = plt.subplots(ncols=2, gridspec_kw={"width_ratios":[15,1]})

im =ax.imshow(Z, vmin=0.1, vmax=1)
cbar = plt.colorbar(im, cax=cax)
cax2 = cax.twinx()

ticks=np.arange(0.1,1.1,0.1)
iticks=1./np.array([10,3,2,1.5,1])
cbar.set_ticks(ticks)
cbar.set_label("z")
cbar.ax.yaxis.set_label_position("left")
cax2.set_ylim(0.1,1)
cax2.set_yticks(iticks)
cax2.set_yticklabels(1./iticks)
cax2.set_ylabel("1/z")

plt.show()

在此输入图片描述


2
请注意,在较新版本的matplotlib中,上述答案已不再适用(正如@Ryan Skene所指出的)。我正在使用v3.3.2。secondary_yaxis函数对于与常规绘图轴相同的色条以相同的方式工作,并提供具有两个刻度的一个色条:https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.secondary_yaxis.html#matplotlib.axes.Axes.secondary_yaxis
import matplotlib.pyplot as plt
import numpy as np

# generate random data
x = np.random.randint(0,200,(10,10)) #let's assume these are temperatures in Fahrenheit
im = plt.imshow(x)

# create the colorbar
cbar = plt.colorbar(im,pad=0.1) #you may need to adjust this padding for the secondary colorbar label[enter image description here][1]
cbar.set_label('Temperature ($^\circ$F)')

# define functions that relate the two colorbar scales
# e.g., Celcius to Fahrenheit and vice versa
def F_to_C(x):
    return (x-32)*5/9
def C_to_F(x):
    return (x*9/5)+32

# create a second axes
cbar2 = cbar.ax.secondary_yaxis('left',functions=(F_to_C,C_to_F))
cbar2.set_ylabel('Temperatrue ($\circ$C)')

plt.show()

0
我正在为我的色条使用一个嵌入轴,但奇怪的是,从v3.4.2版本开始,我发现上述方法不再有效。twinx占据了整个原始子图。
因此,我只是复制了嵌入轴(而不是使用twinx),并增加了原始嵌入轴的zorder值。
axkws = dict(zorder=2)
cax = inset_axes(
    ax, width="100%", height="100%", bbox_to_anchor=bbox, 
    bbox_transform=ax.transAxes, axes_kwargs=axkws
)
cbar = self.fig.colorbar(mpl.cm.ScalarMappable(cmap=cmap), cax=cax)
cbar.ax.yaxis.set_ticks_position('left')
    
caxx = inset_axes(
    ax, width="100%", height="100%", 
    bbox_to_anchor=bbox, bbox_transform=ax.transAxes
)
caxx.yaxis.set_ticks_position('right')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接