首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将面板添加到matplotlib中的条形图

将面板添加到matplotlib中的条形图
EN

Stack Overflow用户
提问于 2016-09-01 01:05:05
回答 1查看 315关注 0票数 2

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

该面板应包含以下内容:

代码语言:javascript
复制
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

下面是我的代码:

代码语言:javascript
复制
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()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-09-01 16:42:53

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

我使用了automatically position text box in matplotlib

代码语言:javascript
复制
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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39255265

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档