如何调整Matplotlib条形图渐变以适配修改后的X轴范围?
问题:Matplotlib条形图渐变颜色无法适配X轴范围修改
我有一个带渐变颜色的水平条形图,当把X轴范围从0-10调整为5-10后,渐变仍然基于原始X轴数值生成,导致新图表里只显示了一半的渐变效果:


我使用以下函数给Matplotlib条形图添加渐变颜色:
def gradientbars(bars): '''Function to apply gradient colour over bars''' grad = np.atleast_2d(np.linspace(0,1,256)) 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, cmap = "Blues") ax.axis(lim)
绘制条形图的函数如下:
def bar_plot(position, x_axis, title): # Opening figure & axis fig, ax = plt.subplots() # Creating scatter plot bar = ax.barh(position['Player'], position[x_axis]) # Applying gradient function gradientbars(bar) # Setting x-axis limits plt.xlim([5, 10])
如何修改代码让渐变适配修改X轴范围后的新图表?
解决方案
问题根源有两点:一是gradientbars函数会强制恢复原始轴范围,覆盖后续设置的X轴限制;二是渐变生成时未考虑当前显示的X轴范围,仍按条形全宽生成渐变。
修改后的代码
1. 调整渐变生成函数
def gradientbars(bars): '''Function to apply gradient colour over bars''' grad = np.atleast_2d(np.linspace(0,1,256)) ax = bars[0].axes # 获取当前X轴的显示范围 x_min, x_max = ax.get_xlim() 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() bar_end = x + w # 渐变从X轴显示起点开始,到条形末端结束 grad_start = max(x_min, x) grad_end = bar_end ax.imshow(grad, extent=[grad_start, grad_end, y, y+h], aspect="auto", zorder=0, cmap="Blues")
2. 调整绘图函数的执行顺序
def bar_plot(position, x_axis, title): # Opening figure & axis fig, ax = plt.subplots() # Creating bar plot bar = ax.barh(position['Player'], position[x_axis]) # 先设置X轴范围,再生成渐变 ax.set_xlim([5, 10]) gradientbars(bar)
关键修改点
- 移除了
gradientbars中强制恢复原始轴范围的代码,让后续设置的X轴限制生效。 - 先设置X轴范围再调用渐变函数,确保渐变生成时能获取到正确的显示边界。
- 渐变的起始点改为X轴的显示最小值(5),让渐变从可见区域的起点开始,填满整个可见的条形部分,解决半截渐变的问题。
内容的提问来源于stack exchange,提问作者codemachine
相关产品推荐
相关产品推荐

