本文介绍了Matplotlib Pandas:在堆叠的条形图中显示列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给出一个熊猫数据框:
response_min \
device_mac 0dd8d 1f3cc 61ff6 623ce
datetime
2016-05-25 08:00:00 0.000000 4.250000 0.250000 0.000000
2016-05-25 12:00:00 0.000000 0.000000 0.000000 0.000000
2016-05-25 16:00:00 0.000000 0.000000 0.000000 0.000000
2016-05-26 08:00:00 12.133333 119.666667 0.250000 0.000000
这样做:
ax = df.plot(kind='bar',stacked=True,logy=True)
for p in ax.patches:
ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))
我得到了:
如何继续在栏中显示列名而不是值?
非常感谢.
(剧透警报)在斯坦利的建议和调试器的帮助下,我设法做到了这一点(注意:对数刻度已关闭):
(Spoiler alert) Following Stanley's advice and the help of the debugger i managed to do it like this (NB: log scale is off):
ax = df.plot(kind='bar',stacked=True,legend=True,width=0.2)
# define a letter for each column
list_column =[ (chr(idx + ord('a')),column) for idx,column in enumerate(list(df.columns.values))]
# set the position of the annotation for each container
def set_text_position(container):
xy_pos = container._rect_transform._a._boxout._points
y_start = xy_pos[0][1]
y_end = xy_pos[1][1]
if y_end-y_start>0:
y_text = (y_start + ((y_end - y_start) / 2))
return y_text
else:
return 0
def set_legend(ax):
for j, column in enumerate(list_column):
ax.legend_.texts[j]._text = list_column[j][0] + " :" + list_column[j][1]
def annotate_bar(ax, i):
for j, column in enumerate(list_column):
height = set_text_position(ax.containers[j][i])
if height > 0:
ax.annotate(column[0], xy=(i, height), xycoords="data",
xytext=(i+0.5, height), va="center", ha="center",
bbox=dict(boxstyle="square", fc="w"),arrowprops=dict(arrowstyle="-"))
for i, label in enumerate(list(df.index)):
annotate_bar(ax, i)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.3), ncol=3, fancybox=True, shadow=True)
set_legend(ax)
ax.margins( 1, None )
ax.set_ylabel('dwell time (minutes)')
ax.set_xlabel("")
推荐答案
类似此处的内容:
import pandas as pd
import matplotlib.pyplot as plt
df=pd.DataFrame({'Devices': [ 'dev1', 'dev2', 'dev3', 'dev4'],
'Response': [4.25,0.,119.,12.1],})
df = df.set_index('Devices')
df.plot(kind='bar', title='Response')
ax = df.plot(kind='bar', title='Response')
ax.set_ylim(0, 130)
for i, label in enumerate(list(df.index)):
height = df.ix[label]['Response']
ax.annotate(str(label), (i, height + 0.3))
plt.show()
这篇关于Matplotlib Pandas:在堆叠的条形图中显示列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!