1 colorbar 按照自定义的最值绘制
归一化方法使用
Normalize(vmin=0, vmax=40.0)
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as mcolors
from matplotlib import rcParams
from matplotlib.colors import ListedColormap
from matplotlib import ticker
from matplotlib.colors import Normalize
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Calibri'
plt.rcParams['font.weight'] = 'bold'
fig, axs = plt.subplots(figsize=(8, 5))
axs.set_visible(False)
# 设置刻度线标签
bins = np.arange(0, 45, 5).tolist() # bins需和最大最小保持一致
nbin = len(bins) - 1
# 归一化设置
norm = Normalize(vmin=0, vmax=40.0)
im = cm.ScalarMappable(norm=norm, cmap='jet')
im.set_array([])
# 绘制
cbar = fig.colorbar(im, ax=axs, orientation='horizontal', drawedges=False)
cbar.set_ticks(bins)
# 设置颜色间隔线的宽度
cbar.dividers.set_linewidth(1.0)
cbar.outline.set_linewidth(1.0)
cbar.update_ticks()
# colorbar属性设置
cbar.ax.tick_params(labelsize=18, direction='out', length=4.0, width=1.4, pad=5.0)
output_dir = r'I:\2019_O3_Average_0420'
output_name = output_dir + '\\' + 'colorbar_0140_0512-6.png'
plt.savefig(output_name, bbox_inches='tight', dpi=500)
得到类似的结果:
如果第一个label和最后一个label不想绘制,更改代码,
但我一直不清楚如果添加单位,除了通过text()
的方法还有什么其他办法
cbar.set_ticks(bins[1:-1])
2 colorbar 按照分类绘制
归一化方法使用
mcolors.BoundaryNorm(bins, nbin)
和第一种方法相比,需要添加cmap的分类
cmap = plt.cm.get_cmap('RdBu_r', nbin)
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as mcolors
from matplotlib import rcParams
from matplotlib.colors import ListedColormap
from matplotlib import ticker
from matplotlib.colors import Normalize
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = 'Calibri'
plt.rcParams['font.weight'] = 'bold'
fig, axs = plt.subplots(figsize=(8, 5))
axs.set_visible(False)
# 设置刻度线标签
bins = np.arange(0, 90, 5).tolist() # bins需和最大最小保持一致
nbin = len(bins) - 1
# 归一化设置
norm = mcolors.BoundaryNorm(bins, nbin)
cmap = plt.cm.get_cmap('RdBu_r', nbin) # 设置颜色 选择你想要的颜色
im = cm.ScalarMappable(norm=norm, cmap=cmap)
im.set_array([])
# 绘制
cbar = fig.colorbar(im, ax=axs, orientation='horizontal', drawedges=False)
cbar.set_ticks(bins)
# 设置颜色间隔线的宽度
cbar.dividers.set_linewidth(1.0)
cbar.outline.set_linewidth(1.0)
cbar.update_ticks()
# colorbar属性设置
cbar.ax.tick_params(labelsize=18, direction='out', length=4.0, width=1.4, pad=5.0)
output_dir = r'I:\2019_O3_Average_0420'
output_name = output_dir + '\\' + 'colorbar_0140_0512-6.png'
plt.savefig(output_name, bbox_inches='tight', dpi=500)
得到类似的结果: