其他解决方案在许多情况下不起作用,因为标签和条之间的间距或者以条的绝对单位给出,或者通过条的高度来缩放。前者仅适用于较窄范围的值,后者在一个图中给出不一致的间距。两者都不适用于对数轴。
我建议的解决方案独立于规模(即小数字和大数字)工作,甚至正确地为负值和对数标度放置标签,因为它使用视觉单位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")