Skip to main content
 首页 » 编程设计

python之不需要的颜色条和轴标签/绘图标题交互

2025年02月15日13mq0036

尊敬的 Python 用户,

我尝试通过将 LinearSegmentedColormap 与 Imshow 结合使用 matplotlib 库来生成颜色图,但我很难使用实际的颜色条。

默认情况下,颜色条的行为不是我想要的,也就是说,它对于我的图表来说太大了。默认情况下,我得到这个:

因此,我引用了 this post 使用以下代码行来修复颜色条高度:

ax = plt.gca() 
divider = make_axes_locatable(ax) 
cax = divider.append_axes("right", size="5%", pad=0.05) 
plt.colorbar(img2, cax=cax) 

然后我得到了这个非常奇怪的结果:

我无法弄清楚为什么添加的代码行与我的轴和绘图标题交互...为什么它们与颜色条一起使用?

完整代码如下:

import matplotlib.pyplot as plt 
import matplotlib.pylab  as pylab 
import matplotlib.colors as colors 
import numpy as np 
from mpl_toolkits.axes_grid1 import make_axes_locatable        
 
#random data for example 
clmap = np.random.rand(30,500) 
 
#plot 2D color map 
fig = plt.figure() 
cmap2 = colors.LinearSegmentedColormap.from_list('my_colormap', ['blue','green','red'], 256) 
img2 = plt.imshow(clmap,interpolation='nearest',cmap = cmap2,origin='lower') 
ax = plt.gca() 
divider = make_axes_locatable(ax) 
cax = divider.append_axes("right", size="5%", pad=0.05) 
fig.colorbar(img2, cmap = cmap2, cax=cax) 
plt.title('color map of atom probab at iteration 1') 
plt.xlabel('atom id') 
plt.ylabel('layer') 
fig.savefig("map_p_1.png") 
plt.gcf().clear() 

请您参考如下方法:

您将 pyplot 状态机 (plt) 与面向对象的 API 混合在一起。
创建第二个坐标区对象 (cax) 后,它将成为当前坐标区。之后出现的所有 pyplot 命令都应用于​​此轴。

最简单的方法是在创建新轴之前应用 pyplot 命令:

import matplotlib.pyplot as plt 
import matplotlib.colors as colors 
import numpy as np 
from mpl_toolkits.axes_grid1 import make_axes_locatable        
 
#random data for example 
clmap = np.random.rand(30,500) 
 
#plot 2D color map 
fig = plt.figure() 
plt.title('color map of atom probab at iteration 1') 
plt.xlabel('atom id') 
plt.ylabel('layer') 
cmap2 = colors.LinearSegmentedColormap.from_list('my_colormap', ['blue','green','red'], 256) 
img2 = plt.imshow(clmap,interpolation='nearest',cmap = cmap2,origin='lower') 
ax = plt.gca() 
divider = make_axes_locatable(ax) 
cax = divider.append_axes("right", size="5%", pad=0.05) 
fig.colorbar(img2, cmap = cmap2, cax=cax) 
 
fig.savefig("map_p_1.png") 
 
plt.show()