在matplotlib条形图上添加值标签

我被卡住了,觉得应该比较容易。 我下面的代码是基于我正在开发的一个更大的项目的示例。 我没有理由发布所有的细节,所以请接受我带来的数据结构。

基本上,我正在创build一个条形图,我可以弄清楚如何在酒吧(在酒吧的中心,或正上方)添加价值标签。 一直在网上看样品,但没有成功实现我自己的代码。 我相信解决办法是用'文本'或'注释',但我:a)不知道使用哪一个(一般来说,还没有弄清楚何时使用哪一个)。 b)看不到要么显示价值标签。 将感谢您的帮助,我的代码如下。 提前致谢!

import numpy as np import pandas as pd import matplotlib.pyplot as plt pd.set_option('display.mpl_style', 'default') %matplotlib inline frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1] # bring some raw data freq_series = pd.Series.from_array(frequencies) # in my original code I create a series and run on that, so for consistency I create a series from the list. x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 121740.0, 123980.0, 126220.0, 128460.0, 130700.0] # now to plot the figure... plt.figure(figsize=(12, 8)) fig = freq_series.plot(kind='bar') fig.set_title("Amount Frequency") fig.set_xlabel("Amount ($)") fig.set_ylabel("Frequency") fig.set_xticklabels(x_labels) 

首先freq_series.plot返回一个轴不是一个数字,所以使我的答案更清楚一点我已经改变了你的给定的代码,把它称为ax而不是fig与其他代码示例更一致。

您可以从ax.patches成员获取图中生成的小节列表。 然后,您可以使用matplotlib库示例中演示的技术,使用ax.text方法添加标签。

 import numpy as np import pandas as pd import matplotlib.pyplot as plt frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1] # bring some raw data freq_series = pd.Series.from_array(frequencies) # in my original code I create a series and run on that, so for consistency I create a series from the list. x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0, 121740.0, 123980.0, 126220.0, 128460.0, 130700.0] # now to 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 # Now 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') plt.savefig("image.png") 

这会产生一个标签图,如下所示:

在这里输入图像描述