【问题标题】:How to increase the spacing between bar plot and bar labels?如何增加条形图和条形标签之间的间距?
【发布时间】:2022-01-24 13:39:53
【问题描述】:

绘图与值(204 kwh、604 kwh、60 kwh)之间的空间太小。如何将这些值移高一点并增加间距?

我有什么:

我想要什么:

代码:

x_name = ['Average\nneighborhood\u00b9', 'Your\nconsumption', 'Efficient\nneighborhood\u00b2']
plt.figure(facecolor='#E2EBF3')
fig = plt.figure(figsize=(12,10))
plt.bar(x_name, val, color =['cornflowerblue', 'saddlebrown', '#196553'],width = .8)
plt.margins(x = .1 , y = 0.25)

plt.xticks(fontsize=25)
plt.yticks([])
 
hfont = {'fontfamily':'serif'}

for index, value in enumerate(np.round(val,2)):
  plt.text(index,value, str(value)+" kWh",fontsize=25, ha='center', va = 'bottom',**hfont)

【问题讨论】:

  • 您的帖子缺少基本代码,因此无法知道应该更改什么。添加一些可重现的测试数据也会有所帮助。根据您创建绘图和添加文本的方式,您可能会尝试在字符串中添加换行符 (123.12 kWh\n ?)。
  • 把文字放高一点,例如plt.text(index,value+50, ...

标签: python matplotlib bar-chart


【解决方案1】:

从 matplotlib 3.4.0 开始,最简单的方法是使用 plt.bar_label 自动标记条形:

  • 设置 padding 以增加条形和标签之间的距离(例如,padding=20
  • 设置fmt来定义格式字符串(例如fmt='%g kWh'添加“kWh”后缀)
bars = plt.bar(x_name, val)                   # store the bar container
plt.bar_label(bars, padding=20, fmt='%g kWh') # auto-label with padding and fmt

请注意,有一个 ax.bar_label 对应项,这对于堆叠/分组条形图特别有用,因为我们可以通过 ax.containers 迭代所有容器:

fig, ax = plt.subplots()
ax.bar(x_name, val1, label='Group 1')
ax.bar(x_name, val2, label='Group 2', bottom=val1)
ax.bar(x_name, val3, label='Group 3', bottom=val2)

# auto-label all 3 bar containers
for c in ax.containers:
    ax.bar_label(c)

【讨论】: