Add date tickers to a matplotlib/python chart

2024/10/3 6:38:43

I have a question that sounds simple but it's driving me mad for some days. I have a historical time series closed in two lists: the first list is containing prices, let's say P = [1, 1.5, 1.3 ...] while the second list is containing the related dates, let's say D = [01/01/2010, 02/01/2010...]. What I would like to do is to plot SOME of these dates (when I say "some" is because the "best" result I got so far is to show all of them as tickers, so creating a black cloud of unreadable data in the x-axis) that, when you zoom in, are shown more in details. This picture is now having the progressive automated range made by Matplotlib:

Zoom-out

Instead of 0, 200, 400 etc. I would like to have the dates values that are related to the data-point plotted. Moreover, when I zoom-in I get the following:

Zoom-in

As well as I get the detail between 0 and 200 (20, 40 etc.) I would like to get the dates attached to the list. I'm sure this is a simple problem to solve but I'm new to Matplotlib as well as to Python and any hint would be appreciated. Thanks in advance

Answer

Matplotlib has sophisticated support for plotting dates. I'd recommend the use of AutoDateFormatter and AutoDateLocator. They are even locale-specific, so they choose month-names according to your locale.

import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocatorxtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)ax = plt.axes()
ax.xaxis.set_major_locator(xtick_locator)
ax.xaxis.set_major_formatter(xtick_formatter)

EDIT

For use with multiple subplots, use multiple locator/formatter pairs:

import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.dates import AutoDateFormatter, AutoDateLocator, date2numx = [datetime.datetime.now() + datetime.timedelta(days=30*i) for i in range(20)]
y = np.random.random((20))xtick_locator = AutoDateLocator()
xtick_formatter = AutoDateFormatter(xtick_locator)for i in range(4):ax = plt.subplot(2,2,i+1)ax.xaxis.set_major_locator(xtick_locator)ax.xaxis.set_major_formatter(xtick_formatter)ax.plot(date2num(x),y)plt.show()
https://en.xdnf.cn/q/70754.html

Related Q&A

Python Selenium: Cant find element by xpath when browser is headless

Im attempting to log into a website using Python Selenium using the following code:import time from contextlib import contextmanager from selenium import webdriver from selenium.webdriver.chrome.option…

Reading large file in Spark issue - python

I have spark installed in local, with python, and when running the following code:data=sc.textFile(C:\\Users\\xxxx\\Desktop\\train.csv) data.first()I get the following error:---------------------------…

pyinstaller: 2 instances of my cherrypy app exe get executed

I have a cherrypy app that Ive made an exe with pyinstaller. now when I run the exe it loads itself twice into memory. Watching the taskmanager shows the first instance load into about 1k, then a seco…

python - Dataframes with RangeIndex vs.Int64Index - Why?

EDIT: I have just found a line in my code that changes my df from a RangeIndex to a numeric Int64Index. How and why does this happen?Before this line all my df are type RangeIndex. After this line of …

Uniform Circular LBP face recognition implementation

I am trying to implement a basic face recognition system using Uniform Circular LBP (8 Points in 1 unit radius neighborhood). I am taking an image, re-sizing it to 200 x 200 pixels and then splitting …

SQLAlchemy declarative one-to-many not defined error

Im trying to figure how to define a one-to-many relationship using SQLAlchemys declarative ORM, and trying to get the example to work, but Im getting an error that my sub-class cant be found (naturally…

Convert numpy.array object to PIL image object

I have been trying to convert a numpy array to PIL image using Image.fromarray but it shows the following error. Traceback (most recent call last): File "C:\Users\Shri1008 SauravDas\AppData\Loc…

Scheduling celery tasks with large ETA

I am currently experimenting with future tasks in celery using the ETA feature and a redis broker. One of the known issues with using a redis broker has to do with the visibility timeout:If a task isn’…

How to read out scroll wheel info from /dev/input/mice?

For a home robotics project I need to read out the raw mouse movement information. I partially succeeded in this by using the python script from this SO-answer. It basically reads out /dev/input/mice a…

Tell me why this does not end up with a timeout error (selenium 2 webdriver)?

from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWaitbrowser = webdriver.Firefox()browser.get("http://testsite.com")element = WebDriverWait(browser, 10).until…