gpt4 book ai didi

python - matplotlib:如何在不在开头和结尾剪裁 NaN 的情况下绘制日期

转载 作者:行者123 更新时间:2023-11-28 17:30:21 26 4
gpt4 key购买 nike

我有值 (np.array) 我想用 ax.plot_date 绘制索引 (DateTimeIndex)。两者的长度相同。

>>>index 
DatetimeIndex(['1997-12-30', '1997-12-31', '1998-01-01', '1998-01-02',
'1998-01-05', '1998-01-06', '1998-01-07', '1998-01-08',
'1998-01-09', '1998-01-12',
...
'2015-12-29', '2015-12-30', '2015-12-31', '2016-01-01',
'2016-01-04', '2016-01-05', '2016-01-06', '2016-01-07',
'2016-01-08', '2016-01-11'],
dtype='datetime64[ns]', length=4705, freq='B')

>>>values
array([ nan, nan, nan, ..., 1.40211106,
1.46409254, 1.36151557])

现在 ax.plot_date(index, values) 工作正常,除了它只会在我想要有间隙的开头(nan)剪裁线。我不知道如何实现这一目标。

最佳答案

您需要手动设置 xtick 标签,这是一个示例,索引中只有 4 个项目,值中有 2 个值:

import pandas as pd
import pylab as plt
import numpy as np

#my made up data
index = pd.DatetimeIndex(['1997-12-30', '1997-12-31', '1998-01-01',
'1998-01-02'])
values = np.array([np.nan, np.nan, 1.402, 1.464])

#we are actually using this array as the x values in our graph, then replacing the labels with dates
x = np.arange(len(index))

#create plot
fig, ax = plt.subplots()
ax.set_xlim([0,len(index)])

#create axes with dates along the x axis
ax.set(xticks=x, xticklabels = index)

#plot values with the corresponding dates
ax.plot_date(x, values)

#show plot
plt.show()

关于python - matplotlib:如何在不在开头和结尾剪裁 NaN 的情况下绘制日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com