鉴于pandas Dataframe:
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 )遵循Stanley的建议并在调试器的帮助下我设法做到这一点(注意:日志刻度已关闭):
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("")
答案 0 :(得分:1)
像这里的东西:
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()