这是我尝试过的:
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
# Define the custom colormap
colors = ['red', 'cyan', 'darkgreen']
cmap = LinearSegmentedColormap.from_list(
'custom_colormap',
[(0.0, colors[0]), (0.5 / 2.0, colors[0]),
(0.5 / 2.0, colors[1]), (1.5 / 2.0, colors[1]),
(1.5 / 2.0, colors[2]), (2.0 / 2.0, colors[2])]
)
# Create a scalar mappable object with the colormap
sm = ScalarMappable(norm=Normalize(vmin=3.5, vmax=4.5), cmap=cmap)
# Create the colorbar
plt.figure(figsize=(3, 1))
cb = plt.colorbar(sm, orientation='horizontal', ticks=[3.5, 4.5], extend='neither')
cb.set_label('')
此代码生成一个类似于您在图片中呈现的颜色条:
from matplotlib.cm import ScalarMappable
from matplotlib.colors import ListedColormap, Normalize
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(6, 1), layout='constrained')
cmap = ListedColormap(["red", "cyan", "slategrey"])
norm = mpl.colors.Normalize(vmin=5, vmax=10)
sm = ScalarMappable(norm=Normalize(2.5,5.5), cmap=cmap)
fig.colorbar(sm, cmap=cmap, ticks=[3.5, 4.5], cax=ax,
orientation='horizontal', label='Colorbar')
plt.show()
cb = plt.colorbar(sm, cmap=cmap, ticks=[3.5, 4.5], cax=ax,
orientation='horizontal', label='Colorbar')
这是你想要的样子吗?