如何在 matplotlib 中禁用日期插值? [英] How to disable date interpolation in matplotlib?

查看:44
本文介绍了如何在 matplotlib 中禁用日期插值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如下所示,它将原始 Pandas 列中没有的日期添加到 x 轴.

我正在使用数据作图(注释行未能成功实现我的目标):

  fig,ax1 = plt.subplots()x_axis = df.index.valuesax1.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()

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

 <代码> 2019-01-09 1.007042 2585.898714 4.052480e + 09 19.980000 12.07 12019-01-10 1.007465 2581.828491 3.704500e+09 19.500000 19.74 12019-01-11 1.007154 2588.605258 3.434490e + 09 18.190001 18.68 12019-01-14 1.008560 2582.151225 3.664450e+09 19.070000 14.27 1

我发现的一些建议包括自定义代码

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

Despite trying some solutions available on SO and at Matplotlib's documentation, I'm still unable to disable Matplotlib's creation of weekend dates on the x-axis.

As you can see see below, it adds dates to the x-axis that are not in the original Pandas column.

I'm plotting my data using (commented lines are unsuccessful in achieving my goal):

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()

An example of my Pandas dataframe is below, with dates as index:

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

Some suggestions I've found include a custom ticker here and here however although I don't get errors the plot is missing my second series.

Any suggestions on how to disable date interpolation in matplotlib?

解决方案

The matplotlib site recommends creating a custom formatter class. This class will contain logic that tells the axis label not to display anything if the date is a weekend. Here's an example using a dataframe I constructed from the 2018 data that was in the image you'd attached:

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'])

  1. Move the dates from the index to their own column:

df = df.reset_index().rename({'index': 'Date'}, axis=1, copy=False)
df['Date'] = pd.to_datetime(df['Date'])

  1. Create the custom formatter class:

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)

  1. Now let's plot the MP and R series. Pay attention to the line where we call the custom formatter:

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()

The above code outputs this graph:

Now, no weekend dates, such as 2018-01-13, are displayed on the x-axis.

这篇关于如何在 matplotlib 中禁用日期插值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆