本文介绍了Matplotlib:在三维条形图中在x轴上格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此,您将如何将数值x轴中的数据转换为格式化的日期/时间字符串?我试图使用ax.xaxis_date()函数而没有成功。我也尝试使用plot_date(),它似乎不适用于3D条形图。以下是示例代码的修改版本,以说明我正在尝试执行的操作:

  from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates

dates = [dates.date2num(datetime.datetime(2009,3,12) )),
dates.date2num(datetime.datetime(2009,6,9)),
dates.date2num(datetime.datetime(2010,1,1)),
#etc。 ($'$'

$ b fig = plt.figure()
ax = Axes3D(fig)
for c,z in zip(['r','g ','b','y'],[30,20,10,0]):
xs = np.array(日期)
ys = np.random.rand(20)
ax.bar(xs,ys,zs = z,zdir ='y',color = c,alpha = 0.8)

ax.set_xlabel('Date& Time')
ax.set_ylabel('Series')
ax.set_zlabel('Amount')

plt.show()


解决方案

Axes3D可能存在一些混淆,轴的属性w_xaxis,w_yaxis和w_zaxis,而不是通常的xaxix,yaxis等。

UPDATE 现在使用函数来标记标签

  from mpl_toolkits.mplot3d import Axes3D 
import matplotlib.pyplot as plt
import numpy as np
导入matplotlib.dates作为日期
导入日期时间,随机
导入matplotlib.ticker作为ticker

def random_date():
date = datetime.date( 2008,12,01)
,而1:
日期+ = datetime.timedelta(天数= 30)
收益率(日期)

def format_date(x,pos = None):
return dates.num2date(x).strftime('%Y-%m-%d')#use使用FuncFormatter格式化日期

r_d = random_date()
some_dates = [dates.date2num(r_d.next())for i in range(0,20)]

fig = plt.fi gure()
ax = Axes3D(fig,rect = [0,0.1,1,1])#为日期标签创建空间

用于c,z in zip(['r' ,'g','b','y'],[30,20,10,0]):
xs = np.array(some_dates)
ys = np.random.rand(20 )
ax.bar(xs,ys,zs = z,zdir ='y',color = c,alpha = 0.8,width = 8)

ax.w_xaxis.set_major_locator(ticker .FixedLocator(some_dates))#我想在ax.w_xaxis.get_ticklabels()中为我的xaxis上的所有日期
ax.w_xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
tl:使用w_xaxis创建什么autofmt_xdate
tl.set_ha('right')
tl.set_rotation(30)

ax.set_ylabel('Series')
ax。 set_zlabel('Amount')

plt.show()

产生:


Given this 3D bar graph sample code, how would you convert the numerical data in the x-axis to formatted date/time strings? I've attempted using the ax.xaxis_date() function without success. I also tried using plot_date(), which doesn't appear to work for 3D bar graphs. Here is a modified version of the sample code to illustrate what I am trying to do:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates

dates = [dates.date2num(datetime.datetime(2009,3,12)),
         dates.date2num(datetime.datetime(2009,6,9)),
         dates.date2num(datetime.datetime(2010,1,1)),
         #etc...
         ]

fig = plt.figure()
ax = Axes3D(fig)
for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
    xs = np.array(dates)
    ys = np.random.rand(20)
    ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8)

ax.set_xlabel('Date & Time')
ax.set_ylabel('Series')
ax.set_zlabel('Amount')

plt.show()

alt text http://matplotlib.sourceforge.net/_images/bars3d_demo1.png

解决方案

There might be some confusion here, the Axes3D has the properties w_xaxis, w_yaxis and w_zaxis for the axises instead of the usual xaxix, yaxis, etc..

UPDATE Now uses function to format labels.

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.dates as dates
import datetime, random
import matplotlib.ticker as ticker

def random_date():
      date = datetime.date(2008, 12,01)
      while 1:
        date += datetime.timedelta(days=30)
        yield (date)

def format_date(x, pos=None):
     return dates.num2date(x).strftime('%Y-%m-%d') #use FuncFormatter to format dates

r_d = random_date()
some_dates = [dates.date2num(r_d.next()) for i in range(0,20)]

fig = plt.figure()
ax = Axes3D(fig,rect=[0,0.1,1,1]) #make room for date labels

for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]):
    xs = np.array(some_dates)
    ys = np.random.rand(20)
    ax.bar(xs, ys, zs=z, zdir='y', color=c, alpha=0.8,width=8)

ax.w_xaxis.set_major_locator(ticker.FixedLocator(some_dates)) # I want all the dates on my xaxis
ax.w_xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
for tl in ax.w_xaxis.get_ticklabels(): # re-create what autofmt_xdate but with w_xaxis
       tl.set_ha('right')
       tl.set_rotation(30)

ax.set_ylabel('Series')
ax.set_zlabel('Amount')

plt.show()

Produces:

alt text http://www.imagechicken.com/uploads/1265570252049424000.png

这篇关于Matplotlib:在三维条形图中在x轴上格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 18:28