如何在水平条形图matplotlib中的多个条形内写入两个文本?

ijxebb2r  于 2023-04-21  发布在  其他
关注(0)|答案(1)|浏览(169)

到目前为止,我的代码给我的东西看起来像这样:

如果可能的话,我想在酒吧里写一些这样的东西:

以下是我目前为止的基本代码:

import pandas
import matplotlib.pyplot as plt
import numpy as np

df = pandas.DataFrame(dict(graph=['Fruits & Vegetables','Bakery'],
                           p=[round(0.942871692205*100,5), round(0.933348641475*100,5)],
                           q=[round(0.941649166881*100,5),round(0.931458324883*100,5)],
                           r=[round(0.940803376393*100,5),round(0.929429068047*100,5)],
                          ))

ind = np.arange(len(df))
width = 0.25

fig, ax = plt.subplots()
ax.barh(ind, df.p, width, color='red', label='Accrate>=80')
ax.barh(ind + width, df.q, width, color='green', label='Accrate>=79')
ax.barh(ind + 2*width, df.r, width, color='blue', label='Accrate>=78')
                           
ax.set(yticks=ind + 2*width, yticklabels=df.graph, ylim=[2*width - 1, len(df)])
ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

我想把数字文本显示在所需的情节链接!我怎么做?

dbf7pr2w

dbf7pr2w1#

我不确定这个数字的逻辑是什么,但是使用ax.text可以这样做:
i = 1 fig,ax = plt.subplots()colors = ['r','g','b '] labels = [80,79,78]

for ii, col in enumerate('pqr'):
    bars = ax.barh(ind + width*ii, df[col], width, color=colors[ii], label=f'Accrate>={labels[ii]}')
    for bar in bars:
        (x,y), h, w = bar.get_xy(), bar.get_height(), bar.get_width()

        ax.text(x+5, y+h/2, str(i), color='w', weight='bold', va='center')
        ax.text(x+w-5, y+h/2, str(6+i), color='w', weight='bold', va='center', ha='right')
        i += 1

输出:

相关问题