Matplotlib:在 3D 条形图中在 x 轴上格式化日期 [英] Matplotlib: Formatting dates on the x-axis in a 3D Bar graph

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

问题描述

鉴于此

解决方案

这里可能有些混乱,Axes3D 具有用于轴的属性 w_xaxis、w_yaxis 和 w_zaxis,而不是通常的 x 轴、y 轴等.

python 3.8.11matplotlib 3.4.3

中测试

from mpl_toolkits.mplot3d import Axes3D导入 matplotlib.pyplot 作为 plt将 numpy 导入为 np导入 matplotlib.dates 作为日期导入日期时间,随机导入 matplotlib.ticker 作为股票代码定义随机日期():日期 = datetime.date(2008, 12, 1)而 1:日期 += datetime.timedelta(days=30)产量(日期)def format_date(x, pos=None):return date.num2date(x).strftime('%Y-%m-%d') #使用FuncFormatter格式化日期r_d = random_date()some_dates = [dates.date2num(next(r_d)) for i in range(0,20)]fig = plt.figure(figsize=(10, 10))ax = fig.add_subplot(projection='3d')对于 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)) # 我想要 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_xaxistl.set_ha('正确')tl.set_rotation(30)ax.set_ylabel('系列')ax.set_zlabel('金额')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()

解决方案

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 x-axis, y-axis, etc.

Tested in python 3.8.11, matplotlib 3.4.3

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, 1)
    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(next(r_d)) for i in range(0,20)]

fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(projection='3d')

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:

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆