Matplotlib为什么colorbar y标签随多个colorbar一起消失

2024-06-28 19:02:42 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么添加第二个颜色栏时,颜色栏标签“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')

enter image description here


Tags: importgsaddmatplotlibstyle颜色asfig
2条回答

在代码中做了两处更正。我也在使用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

结果:

Resulting plots

在adition中,您可以向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')

如果仍然面临此问题,请尝试重新启动内核

这可能是一个错误。打印后可以设置标签:

# Your other codes

# also can use `cbax1` instead of `cbar1.ax`
cbar2.ax.set_ylabel('y2')
cbar2.ax.yaxis.set_label_position('left')

cbar1.ax.set_ylabel('y1')
cbar1.ax.yaxis.set_label_position('left')

输出:

enter image description here

相关问题 更多 >