Skip to main content
 首页 » 编程设计

python之在 matplotlib 中向条形图添加面板

2025年04月02日10duanxz

如何向此条形图添加包含(每个算法的改进百分比)的面板?例如,它应该位于图表的右上角。我这样做是为了让读者更容易看到每个算法与其非贪婪版本相比有多少改进。

面板应包含以下内容:

UB-improvement= (("UB+Greedy"- "UB")/"UB")*100 
IB-improvement=(("IB+Greedy"- "IB")/"IB")*100 
SVD-improvement=(("SVD+Greedy"- "SVD")/"SVD")*100 
TOP_N-improvement=(("TOP_N+Greedy"- "TOP_N")/"TOP_N")*100 

这是我的代码:

import numpy as np 
import matplotlib.pyplot as plt 
N = 1 
ind = np.arange(N)  # the x locations for the groups 
width = 0.2     # the width of the bars 
 
fig = plt.figure() 
ax = plt.subplot(111) 
ub = 5444 
rects1 = ax.bar(ind, ub, width, color='red') 
ub_greedy = 6573 
rects2 = ax.bar(ind+width, ub_greedy, width, color='darkviolet') 
 
ib = 1521 
rects3 = ax.bar(ind+2*width, ib, width, color='black') 
ib_greedy = 5483 
rects4 = ax.bar(ind+3*width, ib_greedy, width, color='blue') 
 
svd=553 
rects5 = ax.bar(ind+4*width, svd, width, color='grey') 
svd_greedy=1225 
rects6 = ax.bar(ind+width*5, svd_greedy, width, color='gold') 
 
pop=7 
rects7 = ax.bar(ind+width*6, pop, width, color='brown') 
pop_greedy=53 
rects8 = ax.bar(ind+width*7, pop_greedy, width, color='lime') 
 
ax.set_ylabel('Owner utilities') 
ax.set_xticklabels('') 
 
ax.set_xticks(ind+width) 
ax.legend((rects1[0], rects2[0], rects3[0],rects4[0],rects5[0], rects6[0], rects7[0],rects8[0]), ('UB','UB+Greedy','IB','IB+Greedy','SVD','SVD+Greedy','TOP_N','TOP_N+Greedy') ,loc='upper center', bbox_to_anchor=(0.5, -0.05), 
          fancybox=True, shadow=True, ncol=8) 
 
def autolabel(rects): 
    for rect in rects: 
        h = rect.get_height() 
        ax.text(rect.get_x()+rect.get_width()/1.9, 1.01*h, '%d'%int(h), 
                ha='center', va='bottom') 
 
autolabel(rects1) 
autolabel(rects2) 
autolabel(rects3) 
autolabel(rects4) 
autolabel(rects5) 
autolabel(rects6) 
autolabel(rects7) 
autolabel(rects8) 
 
plt.title("Total owner utilities for different algorithms",y=1.08) 
plt.show() 

请您参考如下方法:

在 autolabel(rects1) 行之前添加以下代码。 (我用的是python 3)

我用了automatically position text box in matplotlib

from matplotlib.offsetbox import AnchoredText 
def func(greedy, non_greedy): return (greedy - non_greedy)/non_greedy*100 
 
anchored_text = AnchoredText('UB-improvement={:.4}%\n'.format(func(ub_greedy, ub))+ 
'IB-improvement={:.4}%\n'.format(func(ib_greedy, ib))+ 
'SVD-improvement={:.4}%\n'.format(func(svd_greedy, svd))+ 
'TOP_N-improvement={:.4}%\n'.format(func(pop_greedy, pop)), loc=1) 
ax.add_artist(anchored_text)