Python-在matplotlib条形图上添加值标签
我陷入一种感觉应该相对容易的事情上。我在下面提供的代码是基于我正在从事的一个较大项目的示例。我没有理由发布所有详细信息,因此请原样接受我带来的数据结构。
基本上,我正在创建一个条形图,我可以弄清楚如何在条形图上(在条形图的中心或上方)添加值标签。一直在网上查看示例,但在我自己的代码上实现未成功。我相信解决方案是使用“文本”或“注释”,但是我:a)不知道要使用哪个(通常来说,还没有弄清楚何时使用哪个)。b)看不到要显示值标签。感谢你的帮助,下面是我的代码。提前致谢!
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
pd.set_option('display.mpl_style', 'default')
%matplotlib inline
# 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))
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 # 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')