基于对另一个问题的回答中提到的功能,我发现了一种非常普遍适用的解决方案,用于在条形图上放置标签。
,其他解决方案不幸的是没有工作,在很多情况下是因为标签栏之间的间距或者在酒吧的绝对单位给出或由条的高度成比例。前者仅适用于较小范围的值,而后者在一个绘图中给出的间距不一致。两者均不能很好地使用对数轴。
我提出的解决方案与比例无关(即,无论大小),甚至可以正确地为负值和对数比例放置标签,因为它使用了可视单位points
作为偏移量。
在这种情况下,我添加了一个负数来展示标签的正确位置。
每个条形的高度值都用作其标签。其他标签可以轻松地与 Simon的for rect, label in zip(rects, labels)
代码段。
import numpy as np
import pandas as pd
import 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 < 0:
# 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")
编辑:正如barnhillec所建议的,我已经提取了函数中的相关功能。
这将产生以下输出:
使用对数标度(以及对输入数据进行一些调整以显示对数标度),结果如下: