python matplotlib添加标签_在matplotlib条形图上添加值标签

其他解决方案在许多情况下不起作用,因为标签和条之间的间距或者以条的绝对单位给出,或者通过条的高度来缩放。前者仅适用于较窄范围的值,后者在一个图中给出不一致的间距。两者都不适用于对数轴。

我建议的解决方案独立于规模(即小数字和大数字)工作,甚至正确地为负值和对数标度放置标签,因为它使用视觉单位points进行偏移。

我添加了一个负数,以展示在这种情况下标签的正确位置。

每个条的高度值用作它的标签。其他标签可以很容易地与Simon的for rect, label in zip(rects, labels)片段一起使用。import numpy as npimport pandas as pdimport matplotlib.pyplot as plt# Bring some raw data.frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]# In my original code I create a series and run on that,# so for consistency I create a series from the list.freq_series = pd.Series.from_array(frequencies)x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,

121740.0, 123980.0, 126220.0, 128460.0, 130700.0]# Plot the figure.plt.figure(figsize=(12, 8))ax = freq_series.plot(kind='bar')ax.set_title('Amount Frequency')ax.set_xlabel('Amount ($)')ax.set_ylabel('Frequency')ax.set_xticklabels(x_labels)def add_value_labels(ax, spacing=5):

"""Add labels to the end of each bar in a bar chart.

Arguments:

ax (matplotlib.axes.Axes): The matplotlib object containing the axes

of the plot to annotate.

spacing (int): The distance between the labels and the bars.

"""

# For each bar: Place a label

for rect in ax.patches:

# Get X and Y placement of label from rect.

y_value = rect.get_height()

x_value = rect.get_x() + rect.get_width() / 2

# Number of points between bar and label. Change to your liking.

space = spacing        # Vertical alignment for positive values

va = 'bottom'

# If value of bar is negative: Place label below bar

if y_value 

# Invert space to place label below

space *= -1

# Vertically align label at top

va = 'top'

# Use Y value as label and format number with one decimal place

label = "{:.1f}".format(y_value)

# Create annotation

ax.annotate(

label,                      # Use `label` as label

(x_value, y_value),         # Place label at end of the bar

xytext=(0, space),          # Vertically shift label by `space`

textcoords="offset points", # Interpret `xytext` as offset in points

ha='center',                # Horizontally center label

va=va)                      # Vertically align label differently for

# positive and negative values.# Call the function above. All the magic happens there.add_value_labels(ax)plt.savefig("image.png")

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值