如何在matplotlib中向水平条形图添加标签?

时间:2020-02-13 16:17:01

标签: python pandas matplotlib

如何在matplotlib的水平条形图中添加标签?

大家好,我是matplotlib和python新手,我想再次问这个问题,以寻求一些帮助,以了解是否有比当前解决方案更简单的方法来添加每个小节所代表的计数标签找到了。

这是我编写的代码:

from matplotlib.pyplot import figure
figure(num=None, figsize=(8, 24), dpi=80, facecolor='w', edgecolor='k')
df['Name'].value_counts()[:80].plot(kind='barh')

除了在条形位旁边显示标签...

我在这里研究了如何添加标签,因此我将代码更改为此:

x = df['Name']
y = df['Name'].value_counts(ascending=True)
fig, ax = plt.subplots(figsize=(18,20))    
width = 0.75 # the width of the bars 
ind = np.arange(len(y))  # the x locations for the groups
ax.barh(ind, y, width, color="blue")
ax.set_yticks(ind+width/2)
ax.set_yticklabels(y, minor=False)
plt.title('Count of supplies')
plt.xlabel('Count')
plt.ylabel('ylabel')

for i, v in enumerate(y):
    ax.text(v + 100, i + 0, str(v), color='black', fontweight='bold')

但是,现在我的名字与条形没有关联,就像它们在数据框中出现的顺序一样。有没有一种方法可以简单地更改第一个代码或使其正确,以使与条形关联的名称在第二次尝试中正确(与它们所标记的条形分组。)?

图片sorta解释了我的问题: Image sorta explaining my issue:

1 个答案:

答案 0 :(得分:0)

(这并不是真正的答案,因为它已经在评论中得到回答。只是显示它的外观。)

使用y的索引作为Barh图的索引,应将y标签放置在正确的位置上,在相应条的旁边。无需操纵y-ticklabel。条形标签可以保持对齐并垂直居中。可以将右x限制稍微移动一点,以便为最长条形的标签留出空间。

from matplotlib import pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame({'Name': np.random.choice(list('AABBBBBCCCCCDEEF'), 20000)})
y = df['Name'].value_counts(ascending=False)
fig, ax = plt.subplots(figsize=(12,5))
ax.barh(y.index, y, height=0.75, color="slateblue")
plt.title('Count of supplies')
plt.xlabel('Count')
plt.ylabel('ylabel')
_, xmax = plt.xlim()
plt.xlim(0, xmax+300)
for i, v in enumerate(y):
    ax.text(v + 100, i, str(v), color='black', fontweight='bold', fontsize=14, ha='left', va='center')
plt.show()

sample plot