Python:如何在pcolormesh中将日期时间添加到x轴

时间:2015-12-11 20:51:22

标签: python datetime matplotlib

使用matplotlib散点图或线图,我可以将x轴指定为日期时间数组。

from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt

size = 10

# List of Dates
base = datetime.today()
date_list = [base - timedelta(weeks=x) for x in range(0, size)]

plt.figure(1)
a = np.random.random([size])
plt.plot(date_list,a)
plt.xticks(rotation=45)

enter image description here

我想用日期时间作为x轴制作一个pcolormesh图,但得到一个错误

这有效,但不是我想要的......

b = np.random.random([size,size])
plt.figure(2)
c = np.arange(0,size)
plt.pcolormesh(c,c,b)

enter image description here

这引发错误......

plt.figure(3)
plt.pcolormesh(date_list,c,b)

如果你不能用日期时间数组提供pcolormesh,还有另一种方法可以将x轴格式化为日期吗?

2 个答案:

答案 0 :(得分:2)

这样的事情:

Features    Features_selected   Coeff_all   Coef_selected
{[1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12],[13],[14],[15],[16],[17],[18],[19],[20],[21],[22],[23],[24],[25],[26],[27],[28],[29],[30],[31],[32],[33],[34],[35],[36],[37],[38],[39],[40],[41],[42],[43],[44],[45],[46],[47],[48],[49],[50],[51],[52],[53] (...)  {[23],[26],[49],[57],[72],[76],[77],[78],[80],[102],[142],[146],[148],[151],[155],[203],[236],[237]}    {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-0.00506647638801,0,0,0.00214173291413,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.0125487796757,0,0,0,0,0,0,0,-0.0611439140518,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0.0551106356256,0,0,0,0.0229294880725,0.0870627454718 (...)  {-0.00506647638801,0.00214173291413,0.0125487796757,-0.0611439140518,0.0551106356256,0.0229294880725,0.0870627454718,0.239468263125,0.0440983220954,0.0575895639153,0.0027274832634,0.00682172962834,0.00932203929069,0.00697528972051,0.0333308071579,0.2709655 (...)

enter image description here

答案 1 :(得分:0)

我刚刚发现您可以在np.meshgrid中使用dtype之类的日期时间。

这意味着您不必手动格式化时间轴。另外,当您放大绘图时,时间轴也会自动缩放。

plt.pcolormesh(
    *np.meshgrid(time_array, y_axis_array),
    data_2D_array
)

此处time_array.dtype是类似日期时间的对象。到目前为止,我已经尝试过使用pd.Timestamp,我猜想它也应该对其他人也有用