How to include diagrams, characters, annotations, etc. in a time series graph of matplotlib

Asked 2 months ago, Updated 2 months ago, 4 views

I use matplotlib.How do I get the pixel coordinates of the graph?
If the x,y axis is a real number,
I understand that pixel coordinates can be obtained using ax.transData.transform.
However, it does not work when the x coordinates are pd.Timestamp.
How do I get pixel coordinates from a graph of time series data?

python matplotlib

2022-09-30 14:30

1 Answers

Python uses datetime to handle the date and time, but Matplotlib uses its own matplotlib.dates where matplotlib.dates is a floating-point number of days plus 1 from January 1, AD.For example, 0001-01-0106:00 is 1.25.

There is also a helper function for converting matplotlib.dates to datetime. You can use date2num to convert datetime objects to Matplotlib.dates.Use num2date for the reverse translation.

Documentation matplotlib.dates

You can use matplotlib.dates to obtain pixel coordinates using ax.transData.transform.Below is a sample of Motplotlib's Transforms Tutorial to be in chronological order

import numpy as np
import pandas aspd
import matplotlib.pyplot asplt
from matplotlib.dates import date2num
from datetime import datetime

x=pd.date_range('2018-06-01','2018-06-11', freq='1H')
y = (lambdap: p.toordinal())


ydata = xdata
xdisplay, ydisplay=ax.transData.transform_point((xdata,ydata))

bbox=dict(boxstyle="round", fc="0.8")

offset = 72
        (xdata, ydata), xytext=(-2*offset, offset), textcoords='offset points',
        bbox=bbox, arrowprops=arrowprops)

display = ax.annotate('display=(%.1f,%.1f)'%(xdisplay,ydisplay),
               (xdisplay, ydisplay), xytext=(0.5*offset, -offset),
               xycords='figure pixels',
               textcoords = 'offset points',
               bbox=bbox, arrowprops=arrowprops)

Enter a description of the image here

As shown in the sample above, you can include graphics, characters, annotations, etc. in time series graphs without using ax.transData.transform.Matplotlib documentation states that 95% of cases do not require the use of transform.

Also, if you use ax.transData.transform in the GUI, it will be misaligned, but the cause and response will be explained in Transcriptions Tutorial.Using pixel coordinate system conversion takes a lot of effort, so it is better not to use it normally.

Note that datetime.toordinal() is always an integer because it is a conversion of the date portion only, but at midnight it is the same value as matplotlib.dates.

2022-09-30 14:30

If you have any answers or tips

© 2022 OneMinuteCode. All rights reserved.