【发布时间】:2016-09-01 19:24:25
【问题描述】:
我正在绘制特定类别中各个办公室的交叉表。我想整理一个水平堆叠的条形图,其中每个办公室及其价值都被标记。
下面是一些示例代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# create dataframe
df = pd.DataFrame({'office1': [1, np.nan, np.nan],
'office2': [np.nan, 8, np.nan],
'office3': [12, np.nan, np.nan],
'office4': [np.nan, np.nan, 3],
'office5': [np.nan, 5, np.nan],
'office6': [np.nan, np.nan, 7],
'office7': [3, np.nan, np.nan],
'office8': [np.nan, np.nan, 11],
'office9': [np.nan, 6, np.nan]},
index=['catA', 'catB', 'catC'])
# plot dataframe
ax = df.plot.barh(title="Office Breakdown by Category",
legend=False,
figsize=(10,7), stacked=True)
这给了我一个很好的起点:
经过一番研究,我想出了以下代码,可以正确排列“类别”轴上的标签:
def annotateBars(row, ax=ax):
for col in row.index:
value = row[col]
if (str(value) != 'nan'):
ax.text(value/2, labeltonum(row.name), col+","+str(value))
def labeltonum(label):
if label == 'catA':
return 0
elif label == 'catB':
return 1
elif label == 'catC':
return 2
df.apply(annotateBars, ax=ax, axis=1)
但这并不考虑条形的“堆叠”。我还尝试遍历 plot 命令返回的patches 容器(它可以让我检索每个矩形的 x 和 y 位置),但是我失去了与办公室标签的任何连接。
【问题讨论】:
-
另请参阅stack bar plot in matplotlib and add label to each section 和Stacked Bar Chart with Centered Labels,了解那些寻求通用解决方案以仅添加值作为注释的人。
标签: python pandas matplotlib