figtext datetime function matplotlib

时间:2016-08-05 15:12:12

标签: python datetime matplotlib

我正在尝试在matplotlib中的图形中创建一个文本框,其中它给出了创建图形的日期。

我使用matplotlib中的figtext函数在我的图表的右下角创建了一个文本框,但无法弄清楚如何在文本框中包含python datetime函数,以便显示日期。有什么想法吗?

下面的代码和图表:

#Stacked Bar Char- matplotlib
#Create the general blog and the "subplots" i.e. the bars
f, ax1 = plt.subplots(1, figsize=(8,5), dpi=1000)
# Set the bar width
bar_width = 0.50
# positions of the left bar-boundaries
bar_l = [i+1 for i in range(len(df4['Pandas']))] 
# positions of the x-axis ticks (center of the bars as bar labels)
tick_pos = [i+(bar_width/2) for i in bar_l] 

#Stack the negative bars by region
#Start bottom at 0, and then use pandas to add bars together
ax1.bar(bar_l, df4['cats1'], width=bar_width, label='cats',color='R', alpha=.4, align='center', 
        bottom = 0)
ax1.bar(bar_l, df4['dogs1'], width=bar_width,label='dogs',color='#ADD8E6',alpha=.4, fill=True, align='center',
        bottom =(df4['cats1']))
ax1.bar(bar_l, df4['zebras1'], width=bar_width, label='zebras',color='#FFA500',alpha=.4, align='center',
        bottom = np.array(df4['cats1'])+np.array(df4['dogs1']))
ax1.bar(bar_l, df4['pandas1'], width=bar_width, label='pandas', color='b',alpha=.5, fill=True, align='center',
        bottom = np.array(df4['cats1'])+np.array(df4['dogs1'])+np.array(df4['zebras1']))
#Stack the positive bars by region
#Start bottom at 0, and then use pandas to add bars together
ax1.bar(bar_l, df4['cats'], width=bar_width,color='R', alpha=.4, align='center', 
        bottom = 0)
ax1.bar(bar_l, df4['dogs'], width=bar_width,color='#ADD8E6',alpha=.4, fill=True, align='center',
        bottom =(df4['cats']))
ax1.bar(bar_l, df4['zebras'], width=bar_width ,color='#FFA500',alpha=.4, align='center',
        bottom = np.array(df4['cats'])+np.array(df4['dogs']))
ax1.bar(bar_l, df4['pandas'], width=bar_width, color='b',alpha=.5, fill=True, align='center',
        bottom = np.array(df4['cats'])+np.array(df4['dogs'])+np.array(df4['zebras']))

# set the x ticks with names
plt.xticks(tick_pos, df4['Year'],fontsize=10)


# Set the label and legends
plt.title('Animals on the farm', fontweight='bold')
ax1.set_ylim([-1600,1000])
ax1.set_ylabel("Count",fontsize=12)
ax1.set_xlabel("Year",fontsize=12)
plt.legend(loc='upper left', prop={'size':6})
ax1.axhline(y=0, color='k')
ax1.axvline(x=0, color='k')
plt.figtext(0, 0,"Data as of ", wrap=False,
            horizontalalignment='left',verticalalignment ='bottom', fontsize=8)
plt.setp(ax1.get_yticklabels(), rotation='horizontal', fontsize=10)
plt.show()

Graph= Animals on the Farm

2 个答案:

答案 0 :(得分:0)

这是今天日期的一个例子:

import datetime as dt

plt.figtext(0, 0,"Data as of {}".format(dt.date.today().strftime('%Y-%m-%d')), wrap=False,
            horizontalalignment='left',verticalalignment ='bottom', fontsize=8)

答案 1 :(得分:0)

如果您有一个datetime对象,则可以使用strftime方法将其转换为使用所需格式的字符串表示形式:

from datetime import datetime
plt.figtext(0, 0, 'Date as of ' + datetime.now().strftime('%Y-%m-%d'))