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

标签 python pandas matplotlib

我有值 (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/

相关文章:

pandas - 可视化 pandas 分组数据

python - 检查 Python 中的 dict 对象中是否存在属性集合

python - 如何在 Mac Homebrew 软件上更新 python3

python - 从 Python 中的字典中提取彼此不相等的随机键

python - 使用 pandas.read_json 时出现 ValueError

Python:平衡回归分析的数据集(重新排列数据集并填充空白类别)

带有列表参数的 Python sum() 函数

python - 如何根据趋势创建新栏目?

python - 如何在python中绘制密度图?

python - 即使已安装也无法导入 matplotlib