python - 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')
解决方案
在您的代码中进行了两次更正。我也在使用 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')
如果您仍然遇到此问题,请尝试重新启动内核。
推荐阅读
- css - 对于全高 PWA,您如何防止在移动设备上输入焦点时调整高度大小?
- ios - TikTok LoginKit iOS 集成问题
- nagios - 使用nagios核心的升级过程?
- jquery - JQuery 动画不符合预期
- apache-spark - 火花流写入整个数据而不是增量
- python-3.x - ModuleNotFoundError 仅在系统上,但不在 Colab 上
- python - 从具有国家代码和国家名称的 2 个 df 和具有不同 len(11 到 15)电话号码的其他 df 尝试找到每个 ph 号的县代码
- python - 安装 pyinstaller 时出现 PEP 517 错误
- python - 根据特定列替换选定的行值
- html - 隐藏禁用表单字段上的禁用图标