Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
matplotlib/examples/recipes/common_date_problems.py at v3.2.x · matplotlib/matplotlib · GitHub
Skip to content
Navigation Menu
Sign in
Appearance settings
Platform
AI CODE CREATION
GitHub Copilot
Write better code with AI
GitHub Copilot app
Direct agents from issue to merge
MCP Registry
Integrate external tools
DEVELOPER WORKFLOWS
Actions
Automate any workflow
Codespaces
Instant dev environments
Issues
Plan and track work
Code Review
Manage code changes
Code Quality
Enforce quality at merge
APPLICATION SECURITY
GitHub Advanced Security
Find and fix vulnerabilities
Code security
Secure your code as you build
Secret protection
Stop leaks before they start
EXPLORE
Why GitHub
Documentation
Blog
Changelog
Marketplace
View all features
Solutions
BY COMPANY SIZE
Enterprises
Small and medium teams
Startups
Nonprofits
BY USE CASE
App Modernization
DevSecOps
DevOps
CI/CD
View all use cases
BY INDUSTRY
Healthcare
Financial services
Manufacturing
Government
View all industries
View all solutions
Resources
EXPLORE BY TOPIC
AI
Software Development
DevOps
Security
View all topics
EXPLORE BY TYPE
Customer stories
Events & webinars
Ebooks & reports
Business insights
GitHub Skills
SUPPORT & SERVICES
Documentation
Customer support
Community forum
Trust center
Partners
View all resources
Open Source
COMMUNITY
GitHub Sponsors
Fund open source developers
PROGRAMS
Security Lab
Maintainer Community
GitHub Stars
Archive Program
REPOSITORIES
Topics
Trending
Collections
Enterprise
ENTERPRISE SOLUTIONS
Enterprise platform
AI-powered developer platform
AVAILABLE ADD-ONS
GitHub Advanced Security
Enterprise-grade security features
Copilot for Business
Enterprise-grade AI features
Premium Support
Enterprise-grade 24/7 support
Pricing
Search
/
Sign in
Sign up
Appearance settings
You signed in with another tab or window.
Reload
to refresh your session.
You signed out in another tab or window.
Reload
to refresh your session.
You switched accounts on another tab or window.
Reload
to refresh your session.
Dismiss alert
{{ message }}
Uh oh!
There was an error while loading.
Please reload this page
.
matplotlib
/
matplotlib
Public
Uh oh!
There was an error while loading.
Please reload this page
.
Notifications
You must be signed in to change notification settings
Fork
8.5k
Star
23.2k
Code
Issues
1.1k
Pull requests
423
Actions
Projects
Wiki
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Wiki
Security and quality
Insights
Files
Expand file tree
v3.2.x
Breadcrumbs
matplotlib
/
examples
/
recipes
/
common_date_problems.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
92 lines (73 loc) · 3.56 KB
v3.2.x
Breadcrumbs
matplotlib
/
examples
/
recipes
/
common_date_problems.py
Copy path
Top
File metadata and controls
Code
Blame
92 lines (73 loc) · 3.56 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
"""
Fixing common date annoyances
=============================
Matplotlib allows you to natively plots python datetime instances, and
for the most part does a good job picking tick locations and string
formats. There are a couple of things it does not handle so
gracefully, and here are some tricks to help you work around them.
We'll load up some sample date data which contains datetime.date
objects in a numpy record array::
In [63]: datafile = cbook.get_sample_data('goog.npz')
In [64]: r = np.load(datafile)['price_data'].view(np.recarray)
In [65]: r.dtype
Out[65]: dtype([('date', '<M8[D]'), ('', '|V4'), ('open', '<f8'),
('high', '<f8'), ('low', '<f8'), ('close', '<f8'),
('volume', '<i8'), ('adj_close', '<f8')])
In [66]: r.date
Out[66]:
array(['2004-08-19', '2004-08-20', '2004-08-23', ..., '2008-10-10',
'2008-10-13', '2008-10-14'], dtype='datetime64[D]')
The dtype of the NumPy record array for the field ``date`` is ``datetime64[D]``
which means it is a 64-bit `numpy.datetime64` in 'day' units. While this format
is more portable, Matplotlib cannot plot this format natively yet. We can plot
this data by changing the dates to `datetime.date` instances instead, which can
be achieved by converting to an object array::
In [67]: r.date.astype('O')
array([datetime.date(2004, 8, 19), datetime.date(2004, 8, 20),
datetime.date(2004, 8, 23), ..., datetime.date(2008, 10, 10),
datetime.date(2008, 10, 13), datetime.date(2008, 10, 14)],
dtype=object)
The dtype of this converted array is now ``object`` and it is filled with
datetime.date instances instead.
If you plot the data, ::
In [67]: plot(r.date.astype('O'), r.close)
Out[67]: [<matplotlib.lines.Line2D object at 0x92a6b6c>]
you will see that the x tick labels are all squashed together.
"""
import
matplotlib
.
cbook
as
cbook
import
matplotlib
.
dates
as
mdates
import
numpy
as
np
import
matplotlib
.
pyplot
as
plt
with
cbook
.
get_sample_data
(
'goog.npz'
)
as
datafile
:
r
=
np
.
load
(
datafile
)[
'price_data'
].
view
(
np
.
recarray
)
# Matplotlib prefers datetime instead of np.datetime64.
date
=
r
.
date
.
astype
(
'O'
)
fig
,
ax
=
plt
.
subplots
()
ax
.
plot
(
date
,
r
.
close
)
ax
.
set_title
(
'Default date handling can cause overlapping labels'
)
###############################################################################
# Another annoyance is that if you hover the mouse over the window and
# look in the lower right corner of the matplotlib toolbar
# (:ref:`navigation-toolbar`) at the x and y coordinates, you see that
# the x locations are formatted the same way the tick labels are, e.g.,
# "Dec 2004".
#
# What we'd like is for the location in the toolbar to have
# a higher degree of precision, e.g., giving us the exact date out mouse is
# hovering over. To fix the first problem, we can use
# :func:`matplotlib.figure.Figure.autofmt_xdate` and to fix the second
# problem we can use the ``ax.fmt_xdata`` attribute which can be set to
# any function that takes a scalar and returns a string. matplotlib has
# a number of date formatters built in, so we'll use one of those.
fig
,
ax
=
plt
.
subplots
()
ax
.
plot
(
date
,
r
.
close
)
# rotate and align the tick labels so they look better
fig
.
autofmt_xdate
()
# use a more precise date string for the x axis locations in the
# toolbar
ax
.
fmt_xdata
=
mdates
.
DateFormatter
(
'%Y-%m-%d'
)
ax
.
set_title
(
'fig.autofmt_xdate fixes the labels'
)
###############################################################################
# Now when you hover your mouse over the plotted data, you'll see date
# format strings like 2004-12-01 in the toolbar.
plt
.
show
()
You can’t perform that action at this time.