首页 > 解决方案 > Matplotlib为什么颜色条y标签会随着多个颜色条消失

问题描述

添加第二个颜色条时,为什么我的颜色条标签“y1”会消失?

如果我删除 ax2 的颜色条,则标签会显示在第一个颜色条上。

使用 Python 3.8

独立代码

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.colors as mcolors
%matplotlib inline 
plt.style.use('seaborn-whitegrid')
    
x = [-15000, -2000, 0, 5000, 6000, 11000, 18000, 21000, 25000, 36000, 62000]
beta = [1000, 200, -800, 100, 1000, -2000, -5000, -5000, -15000, -21000, -1500]
y = [0.01, 0.2, 1.3, 0.35, 0.88, 2.2, 2.5, 1.25, 3.4, 4.1, 2.1]

fig = plt.figure(figsize=(10, 7.5), constrained_layout=True)
gs = fig.add_gridspec(2, 1)
ax1 = fig.add_subplot(gs[0, 0])
ax2 = fig.add_subplot(gs[1, 0], sharex = ax1)
fig.execute_constrained_layout()
fig.suptitle('Suptitle')


vals = ax1.scatter(x, beta, c=y, norm=mcolors.LogNorm(), cmap='rainbow')
ax1.set_title('ax1', style='italic');
cbax1=ax1.inset_axes([1.1, 0, 0.03, 1], transform=ax1.transAxes)
cbar1=fig.colorbar(vals, cax=cbax1, format = '%1.2g', orientation='vertical')
cbar1.ax.set_ylabel('y1')
cbar1.ax.yaxis.set_label_position('left')

ax2.scatter(x, y, c=y, norm=mcolors.LogNorm(), cmap='rainbow')
ax2.set_title('ax2', style='italic');
vals2 = vals
cbax2 = ax2.inset_axes([1.1, 0, 0.03, 1], transform=ax2.transAxes)
cbar2 = fig.colorbar(vals2, cax=cbax2, format = '%1.2g', orientation='vertical')
cbar2.ax.set_ylabel('y2')
cbar2.ax.yaxis.set_label_position('left')

在此处输入图像描述

标签: pythonmatplotlibaxis-labelscolorbar

解决方案


在您的代码中进行了两次更正。我也在使用 Python 3.8

# ---> Assign the second scatter plot to vals2
vals2 = ax2.scatter(x, y, c=y, norm=mcolors.LogNorm(), cmap='rainbow')
ax2.set_title('ax2', style='italic');
# ---> comment below line.
#vals2 = vals

结果:

结果图

此外,您可以像这样向 colorbar() 函数添加标签:

cbar1=fig.colorbar(vals, cax=cbax1, format = '%1.2g', orientation='vertical', label='y1')
cbar2 = fig.colorbar(vals2, cax=cbax2, format = '%1.2g', orientation='vertical', label='y2')

如果您仍然遇到此问题,请尝试重新启动内核。


推荐阅读