我从matplotlib用户邮件列表的Ryan获得了解决方案。非常优雅,因此我在这里分享他的例子:
import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.patches import Rectanglefrom matplotlib.collections import PatchCollectionn = 100# Get your xy data points, which are the centers of the rectangles.xy = np.random.rand(n,2)# Set a fixed heightheight = 0.02# The variable widths of the rectangleswidths = np.random.rand(n)*0.1# Get a color map and make some colorscmap = plt.cm.hsvcolors = np.random.rand(n)*10.# Make a normalized array of colorscolors_norm = colors/colors.max()# Here's where you have to make a ScalarMappable with the colormapmappable = plt.cm.ScalarMappable(cmap=cmap)# Give it your non-normalized color datamappable.set_array(colors)rects = []for p, w in zip(xy, widths): xpos = p[0] - w/2 # The x position will be half the width from the center ypos = p[1] - height/2 # same for the y position, but with height rect = Rectangle( (xpos, ypos), w, height ) # Create a rectangle rects.append(rect) # Add the rectangle patch to our list# Create a collection from the rectanglescol = PatchCollection(rects)# set the alpha for all rectanglescol.set_alpha(0.3)# Set the colors using the colormapcol.set_facecolor( cmap(colors_norm) )# No linescol.set_linewidth( 0 )#col.set_edgecolor( 'none' )# Make a figure and add the collection to the axis.fig = plt.figure()ax = fig.add_subplot(111)ax.add_collection(col)# Add your ScalarMappable to a figure colorbarfig.colorbar(mappable)plt.show()
谢谢Ryan,以及所有贡献自己想法的人!



