如何在matplotlib中禁用日期插值?

pep*_*epe 5 python matplotlib dataframe pandas

尽管在SO和Matplotlib的文档中尝试了一些解决方案,我仍然无法禁用Matplotlib在x轴上创建周末日期.

如您所见,它会向x轴添加不在原始Pandas列中的日期.

在此输入图像描述

我正在使用(评论的行不能成功实现我的目标)来绘制我的数据:

fig, ax1 = plt.subplots()

x_axis = df.index.values
ax1.plot(x_axis, df['MP'], color='k')
ax2 = ax1.twinx()
ax2.plot(x_axis, df['R'], color='r')

# plt.xticks(np.arange(len(x_axis)), x_axis)
# fig.autofmt_xdate()
# ax1.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

下面是我的Pandas数据框的示例,日期为索引:

2019-01-09  1.007042  2585.898714  4.052480e+09  19.980000  12.07     1
2019-01-10  1.007465  2581.828491  3.704500e+09  19.500000  19.74     1
2019-01-11  1.007154  2588.605258  3.434490e+09  18.190001  18.68     1
2019-01-14  1.008560  2582.151225  3.664450e+09  19.070000  14.27     1
Run Code Online (Sandbox Code Playgroud)

我发现的一些建议包括这里这里的自定义自动收报机,但是虽然我没有得到错误,但情节缺少我的第二个系列.

有关如何在matplotlib中禁用日期插值的任何建议?

小智 3

matplotlib 站点建议创建一个自定义格式化程序类。此类将包含告诉轴标签在日期是周末时不要显示任何内容的逻辑。下面是一个使用我根据附加图像中的 2018 年数据构建的数据框的示例:

df = pd.DataFrame(
data = {
 "Col 1" : [1.000325, 1.000807, 1.001207, 1.000355, 1.001512, 1.003237, 1.000979],
 "MP": [2743.002071, 2754.011543, 2746.121450, 2760.169848, 2780.756857, 2793.953050, 2792.675162],
 "Col 3": [3.242650e+09, 3.453480e+09, 3.576350e+09, 3.641320e+09, 3.573970e+09, 3.573970e+09, 4.325970e+09], 
 "Col 4": [9.520000, 10.080000, 9.820000, 9.880000, 10.160000, 10.160000, 11.660000],
 "Col 5": [5.04, 5.62, 5.29, 6.58, 8.32, 9.57, 9.53],
 "R": [0,0,0,0,0,1,1]
}, 
index=['2018-01-08', '2018-01-09', '2018-01-10', '2018-01-11',
       '2018-01-12', '2018-01-15', '2018-01-16'])
Run Code Online (Sandbox Code Playgroud)
  1. 将日期从索引移动到它们自己的列:
df = df.reset_index().rename({'index': 'Date'}, axis=1, copy=False)
df['Date'] = pd.to_datetime(df['Date'])
Run Code Online (Sandbox Code Playgroud)
  1. 创建自定义格式化程序类:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import Formatter
%config InlineBackend.figure_format = 'retina' # Get nicer looking graphs for retina displays

class CustomFormatter(Formatter):
    def __init__(self, dates, fmt='%Y-%m-%d'):
        self.dates = dates
        self.fmt = fmt

    def __call__(self, x, pos=0):
        'Return the label for time x at position pos'
        ind = int(np.round(x))
        if ind >= len(self.dates) or ind < 0:
            return ''

        return self.dates[ind].strftime(self.fmt)
Run Code Online (Sandbox Code Playgroud)
  1. 现在让我们绘制MPR级数。注意我们调用自定义格式化程序的行:
formatter = CustomFormatter(df['Date'])

fig, ax1 = plt.subplots()
ax1.xaxis.set_major_formatter(formatter)
ax1.plot(np.arange(len(df)), df['MP'], color='k')
ax2 = ax1.twinx()
ax2.plot(np.arange(len(df)), df['R'], color='r')
fig.autofmt_xdate()
fig.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)

上面的代码输出这个图: 输出图

现在,x 轴上不会显示周末日期,例如 2018-01-13。