Matplotlib:具有颜色范围的水平条形图

Matplotlib : Horizontal Bar Plot with Color Range

请原谅粗略的解释,但我不确定如何描述这个问题,正如他们所说,一张图片说一千个字,所以我想要实现的是在 matplotlib 中绘制一个看起来像以下: 由此,所有条形的颜色范围比例与 x-axis.

的 x 限制相同

到目前为止我最接近的是这个(请忽略它不是水平的事实 - 我打算在弄清楚颜色后编辑它):

fig, ax = plt.subplots()
mpl.pyplot.viridis()
bars = ax.bar(df['Profile'], df['noise_result'])
grad = np.atleast_2d(np.linspace(0,1,256)).T
ax = bars[0].axes
lim = ax.get_xlim()+ax.get_ylim()
for bar in bars:
    bar.set_zorder(1)
    bar.set_facecolor('none')
    x,y = bar.get_xy()
    w, h = bar.get_width(), bar.get_height()
    ax.imshow(grad, extent=[x,x+w,y,y+h], aspect='auto', zorder=1,interpolation='nearest')
ax.axis(lim)

这只会产生如下图:

非常感谢

我同意你的做法。想法是:

  1. 选择合适的颜色图
  2. 为条值创建一个标准化器。
  3. 创建一个可映射对象,它将规范化的值映射到颜色图以创建颜色条。
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.colors import Normalize
import pandas as pd
import numpy as np

df = pd.DataFrame({'key':['A', 'B', 'C', 'D', 'E'], 'val':[100, 20, 70, 40, 100]})

# create a normalizer
norm = Normalize(vmin=df['val'].min(), vmax=df['val'].max())
# choose a colormap
cmap = cm.plasma
# map values to a colorbar
mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
mappable.set_array(df['val'])


fig, ax = plt.subplots()
bars = ax.bar(df['key'], df['val'])

ax = bars[0].axes
lim = ax.get_xlim()+ax.get_ylim()
for bar, val in zip(bars, df['val']):
    grad = np.atleast_2d(np.linspace(0,val,256)).T
    bar.set_zorder(1)
    bar.set_facecolor('none')
    x, y = bar.get_xy()
    w, h = bar.get_width(), bar.get_height()
    ax.imshow(np.flip(grad), extent=[x,x+w,y,y+h], aspect='auto', zorder=1,interpolation='nearest', cmap=cmap, norm=norm)
ax.axis(lim)
cb = fig.colorbar(mappable)
cb.set_label("Values")

利用现有资源,您可以将第 12 行更改为: ax.imshow(grad, extent=[x,x+w,y,y+h], aspect='auto', zorder=1, cmap = plt.get_cmap('gist_heat_r') ) 或来自以下的一些其他颜色图: https://matplotlib.org/stable/tutorials/colors/colormaps.html 您还可以将第 3 行更改为开始: 酒吧 = ax.barh 对于单杠。