如何在 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')
但是,现在我的名字与条形无关,并且就像它们在数据框中出现的顺序一样。有没有一种方法可以简单地更改第一个代码或使其与条形相关的名称在第二次尝试中正确(与它们标记的条形分组..)?
最佳答案
使用 y 的索引作为条形图的索引应该将 y 标签放在相应条形旁边的正确位置。无需操作 y 刻度标签。条形标签可以左对齐并垂直居中。右侧的 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()
关于python - 如何在 matplotlib 中向水平条形图添加标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60212294/