将值标签添加到Pandas数据框条形图时遇到问题

时间:2016-03-16 21:19:39

标签: python pandas matplotlib

我一直在努力为Pandas数据框条形图添加一个简单的值标签。我查看过20多个帖子(这三个帖子最有帮助 - How can I display text over columns in a bar chart in matplotlib?matplotlib advanced bar plotPython pandas / matplotlib annotating labels above bar chart columns,但没有任何效果。

我的数据并不复杂。数据帧结构是:

+------+----------+----------+----------+----------+-------+
| Year | Product1 | Product2 | Product3 | Product4 | Total |
+------+----------+----------+----------+----------+-------+
| 2005 |      123 |      123 |      123 |      123 |   492 |
| 2006 |      111 |      111 |      111 |      111 |   444 |
+------+----------+----------+----------+----------+-------+

年份是数据框的索引。

我正在寻找的表现很简单。所有产品的堆积条形图,仅包含' Total'的值标签。显示在堆积列的顶部(我不想在图表中表示“Total'”)。

我目前的代码是:

fig,ax = plt.subplots()
ax =df.ix[:,df.columns.difference(['Total'])].plot.bar(stacked=True, colormap='coolwarm',figsize=(14,12),ax=ax)
ax.set_ylabel("Total sales", fontsize=14)
ax.set_xlabel("Year", fontsize=14)
ax.legend(loc='best', fancybox=True, framealpha=0.5)
for i, label in enumerate(list(df.index)):
    score = df.ix[label]['Total']
    ax.annotate(str(score), (i - 0.2, score))
fig = ax.get_figure()
fig.savefig('sumplot.png',dpi=100,bbox='Tight')

我现在所获得的是在天空中消失的价值观。我认为这是因为高度取决于所有其他列的' +&+ 39; +值?无论如何要修改它,以便高度只是' Total&#39 ;?的高度摆弄ax.annotate片段中的得分值没有帮助,因为数据值存在很大差异(上面的数据结构只是代表性而非实际数据)

1 个答案:

答案 0 :(得分:0)

我运行了以下代码,并没有做太多修改。我所做的只是将年份设置为数据框的索引,并将.ix更新为.loc方法调用。

您的问题可能是由于不是根据年份绘制,而是根据数字索引而引起的,该数字索引随后将年份作为要绘制的值包括在您感兴趣的数据之上。

如果我正确理解了您的问题,则以下代码将产生所需的结果。我将为我的地块做广告,供您验证。

Plot of data

import matplotlib.pyplot as plt
import pandas as pd

data = {
    "Year": [2005, 2006],
    "Product1": [123, 111],
    "Product2": [123, 111],
    "Product3": [123, 111],
    "Product4": [123, 111],
    "Total": [492, 444]
}

df = pd.DataFrame(data).set_index("Year", drop=True)

fig,ax = plt.subplots()
ax =df.loc[:,df.columns.difference(['Total'])].plot.bar(stacked=True, colormap='coolwarm',figsize=(14,12),ax=ax)
ax.set_ylabel("Total sales", fontsize=14)
ax.set_xlabel("Year", fontsize=14)
ax.legend(loc='best', fancybox=True, framealpha=0.5)
for i, label in enumerate(list(df.index)):
    score = df.loc[label]['Total']
    ax.annotate(str(score), (i - 0.2, score))
fig = ax.get_figure()
fig.savefig('sumplot.png',dpi=100,bbox='Tight')