3 回答
TA贡献1848条经验 获得超10个赞
首先freq_series.plot返回一个轴而不是一个数字,以便让我的答案更加清晰我已经改变了你的给定代码来引用它,ax而不是fig与其他代码示例更加一致。
您可以从ax.patches成员中获取绘图中生成的条形列表。然后,您可以使用此matplotlib库示例中演示的技术使用该ax.text方法添加标签。
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)
rects = ax.patches
# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
ha='center', va='bottom')
这会产生一个标记的图,看起来像:
TA贡献1803条经验 获得超3个赞
基于上述(很棒!)答案,我们还可以通过一些调整来制作水平条形图:
# Bring some raw data.frequencies = [6, -16, 75, 160, 244, 260, 145, 73, 16, 4, 1]freq_series = pd.Series(frequencies)y_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='barh')ax.set_title('Amount Frequency')ax.set_xlabel('Frequency')ax.set_ylabel('Amount ($)')ax.set_yticklabels(y_labels)ax.set_xlim(-40, 300) # expand xlim to make labels easier to readrects = ax.patches# For each bar: Place a labelfor rect in rects: # Get X and Y placement of label from rect. x_value = rect.get_width() y_value = rect.get_y() + rect.get_height() / 2 # Number of points between bar and label. Change to your liking. space = 5 # Vertical alignment for positive values ha = 'left' # If value of bar is negative: Place label left of bar if x_value < 0: # Invert space to place label to the left space *= -1 # Horizontally align label at right ha = 'right' # Use X value as label and format number with one decimal place label = "{:.1f}".format(x_value) # Create annotation plt.annotate( label, # Use `label` as label (x_value, y_value), # Place label at end of the bar xytext=(space, 0), # Horizontally shift label by `space` textcoords="offset points", # Interpret `xytext` as offset in points va='center', # Vertically center label ha=ha) # Horizontally align label differently for # positive and negative values.plt.savefig("image.png")
添加回答
举报