How to disable date interpolation in matplotlib?

2024/11/16 3:41:52

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.

enter image description here

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?

Answer

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 displaysclass CustomFormatter(Formatter):def __init__(self, dates, fmt='%Y-%m-%d'):self.dates = datesself.fmt = fmtdef __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: Output graph

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

https://en.xdnf.cn/q/71385.html

Related Q&A

Continuous error band with Plotly Express in Python [duplicate]

This question already has answers here:Plotly: How to make a figure with multiple lines and shaded area for standard deviations?(5 answers)Closed 2 years ago.I need to plot data with continuous error …

How to preprocess training set for VGG16 fine tuning in Keras?

I have fine tuned the Keras VGG16 model, but Im unsure about the preprocessing during the training phase.I create a train generator as follow:train_datagen = ImageDataGenerator(rescale=1./255) train_ge…

Using Python like PHP in Apache/Windows

I understand that I should use mod_wsgi to run Python, and I have been trying to get that set up, but Im confused about it:This is a sample configuration I found for web.py:LoadModule wsgi_module modul…

django-oauth-toolkit : Customize authenticate response

I am new to Django OAuth Toolkit. I want to customize the authenticate response.My authenticate url configuration on django application is : url(authenticate/,include(oauth2_provider.urls, namespace=oa…

Pushing local branch to remote branch

I created new repository in my Github repository.Using the gitpython library Im able to get this repository. Then I create new branch, add new file, commit and try to push to the new branch.Please chec…

Does Pandas, SciPy, or NumPy provide a cumulative standard deviation function?

I have a Pandas series. I need to get sigma_i, which is the standard deviation of a series up to index i. Is there an existing function which efficiently calculates that? I noticed that there are the …

Python: compile into an Unix commandline app

I am not sure if I searched for the wrong terms, but I could not find much on this subject. I am on osx and Id like to compile a commandline python script into a small commandline app, that I can put i…

ModuleNotFoundError in PySpark Worker on rdd.collect()

I am running an Apache Spark program in python, and I am getting an error that I cant understand and cant begin to debug. I have a driver program that defines a function called hound in a file called h…

Sphinx is not able to import anything

I am trying to use sphinx to document a project of mine. I have used autodoc strings within all of my modules and files. I used sphinx-apidoc to automatically generate rst files for my code. So far, so…

Python : why a method from super class not seen?

i am trying to implement my own version of a DailyLogFile from twisted.python.logfile import DailyLogFileclass NDailyLogFile(DailyLogFile):def __init__(self, name, directory, rotateAfterN = 1, defaultM…