English 中文(简体)
Matplotlib: Formatting dates on the x-axis in a 3D Bar graph
原标题:

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

最佳回答

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:

enter image description here

问题回答

暂无回答




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签