在matplotlib条形图上添加值标签

在matplotlib条形图上添加值标签

我被困在一些感觉应该相对容易的事情上。我下面的代码是基于我正在研究的更大项目的示例。我没有理由发布所有细节,所以请接受我带来的数据结构。


基本上,我正在创建一个条形图,我只是想弄清楚如何在条形图上添加值标签(在条形图的中心,或者在它上面)。一直在寻找网络上的样本,但没有成功实现我自己的代码。我相信解决方案要么是'text',要么是'annotate',但我: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)


白衣染霜花
浏览 2740回答 3
3回答

慕桂英546537

首先freq_series.plot返回一个轴而不是一个数字,以便让我的答案更加清晰我已经改变了你的给定代码来引用它,ax而不是fig与其他代码示例更加一致。您可以从ax.patches成员中获取绘图中生成的条形列表。然后,您可以使用此matplotlib库示例中演示的技术使用该ax.text方法添加标签。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)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')这会产生一个标记的图,看起来像:

繁星点点滴滴

基于上述(很棒!)答案,我们还可以通过一些调整来制作水平条形图:#&nbsp;Bring&nbsp;some&nbsp;raw&nbsp;data.frequencies&nbsp;=&nbsp;[6,&nbsp;-16,&nbsp;75,&nbsp;160,&nbsp;244,&nbsp;260,&nbsp;145,&nbsp;73,&nbsp;16,&nbsp;4,&nbsp;1]freq_series&nbsp;=&nbsp;pd.Series(frequencies)y_labels&nbsp;=&nbsp;[108300.0,&nbsp;110540.0,&nbsp;112780.0,&nbsp;115020.0,&nbsp;117260.0,&nbsp;119500.0,&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;121740.0,&nbsp;123980.0,&nbsp;126220.0,&nbsp;128460.0,&nbsp;130700.0]#&nbsp;Plot&nbsp;the&nbsp;figure.plt.figure(figsize=(12,&nbsp;8))ax&nbsp;=&nbsp;freq_series.plot(kind='barh')ax.set_title('Amount&nbsp;Frequency')ax.set_xlabel('Frequency')ax.set_ylabel('Amount&nbsp;($)')ax.set_yticklabels(y_labels)ax.set_xlim(-40,&nbsp;300)&nbsp;#&nbsp;expand&nbsp;xlim&nbsp;to&nbsp;make&nbsp;labels&nbsp;easier&nbsp;to&nbsp;readrects&nbsp;=&nbsp;ax.patches#&nbsp;For&nbsp;each&nbsp;bar:&nbsp;Place&nbsp;a&nbsp;labelfor&nbsp;rect&nbsp;in&nbsp;rects: &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Get&nbsp;X&nbsp;and&nbsp;Y&nbsp;placement&nbsp;of&nbsp;label&nbsp;from&nbsp;rect. &nbsp;&nbsp;&nbsp;&nbsp;x_value&nbsp;=&nbsp;rect.get_width() &nbsp;&nbsp;&nbsp;&nbsp;y_value&nbsp;=&nbsp;rect.get_y()&nbsp;+&nbsp;rect.get_height()&nbsp;/&nbsp;2 &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Number&nbsp;of&nbsp;points&nbsp;between&nbsp;bar&nbsp;and&nbsp;label.&nbsp;Change&nbsp;to&nbsp;your&nbsp;liking. &nbsp;&nbsp;&nbsp;&nbsp;space&nbsp;=&nbsp;5 &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Vertical&nbsp;alignment&nbsp;for&nbsp;positive&nbsp;values &nbsp;&nbsp;&nbsp;&nbsp;ha&nbsp;=&nbsp;'left' &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;If&nbsp;value&nbsp;of&nbsp;bar&nbsp;is&nbsp;negative:&nbsp;Place&nbsp;label&nbsp;left&nbsp;of&nbsp;bar &nbsp;&nbsp;&nbsp;&nbsp;if&nbsp;x_value&nbsp;<&nbsp;0: &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Invert&nbsp;space&nbsp;to&nbsp;place&nbsp;label&nbsp;to&nbsp;the&nbsp;left &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;space&nbsp;*=&nbsp;-1 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Horizontally&nbsp;align&nbsp;label&nbsp;at&nbsp;right &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ha&nbsp;=&nbsp;'right' &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Use&nbsp;X&nbsp;value&nbsp;as&nbsp;label&nbsp;and&nbsp;format&nbsp;number&nbsp;with&nbsp;one&nbsp;decimal&nbsp;place &nbsp;&nbsp;&nbsp;&nbsp;label&nbsp;=&nbsp;"{:.1f}".format(x_value) &nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Create&nbsp;annotation &nbsp;&nbsp;&nbsp;&nbsp;plt.annotate( &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;label,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Use&nbsp;`label`&nbsp;as&nbsp;label &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;(x_value,&nbsp;y_value),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Place&nbsp;label&nbsp;at&nbsp;end&nbsp;of&nbsp;the&nbsp;bar &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;xytext=(space,&nbsp;0),&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Horizontally&nbsp;shift&nbsp;label&nbsp;by&nbsp;`space` &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;textcoords="offset&nbsp;points",&nbsp;#&nbsp;Interpret&nbsp;`xytext`&nbsp;as&nbsp;offset&nbsp;in&nbsp;points &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;va='center',&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Vertically&nbsp;center&nbsp;label &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ha=ha)&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;Horizontally&nbsp;align&nbsp;label&nbsp;differently&nbsp;for &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;#&nbsp;positive&nbsp;and&nbsp;negative&nbsp;values.plt.savefig("image.png")
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python