Skip to main content
 首页 » 编程设计

python之如何用渐变填充 matplotlib 条形图

2025年05月04日15linjiqin

我非常有兴趣用不同的梯度填充 barplot 的 matplotlib/seaborn 条,就像这里所做的那样(据我所知,不是用 matplotlib):

我也检查了这个相关主题Pyplot: vertical gradient fill under curve? .

这是否只能通过 gr-framework 实现: 还是有替代策略?

请您参考如下方法:

正如Pyplot: vertical gradient fill under curve?中描述的那样人们可以使用图像来创建梯度图。

由于条形图是矩形的,因此图像的范围可以直接设置为条形图的位置和大小。可以遍历所有条形并在相应位置创建图像。结果是一个梯度条形图。

import numpy as np 
import matplotlib.pyplot as plt 
 
fig, ax = plt.subplots() 
 
bar = ax.bar([1,2,3,4,5,6],[4,5,6,3,7,5]) 
 
def gradientbars(bars): 
    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=0) 
    ax.axis(lim) 
 
gradientbars(bar) 
 
plt.show()