Home
About
Blog
Products
Forum
Support
Contact
Sunbelt Computer Software
PL/B Language Development and Support
Home
About
Blog
Products
Forum
Support
Contact
matplotlib/lib/matplotlib/units.py at main · story645/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 }}
story645
/
matplotlib
Public
forked from
matplotlib/matplotlib
Notifications
You must be signed in to change notification settings
Fork
1
Star
1
Code
Issues
17
Pull requests
3
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
main
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
units.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
195 lines (160 loc) · 6.28 KB
main
Breadcrumbs
matplotlib
/
lib
/
matplotlib
/
units.py
Copy path
Top
File metadata and controls
Code
Blame
195 lines (160 loc) · 6.28 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
"""
The classes here provide support for using custom classes with
Matplotlib, e.g., those that do not expose the array interface but know
how to convert themselves to arrays. It also supports classes with
units and units conversion. Use cases include converters for custom
objects, e.g., a list of datetime objects, as well as for objects that
are unit aware. We don't assume any particular units implementation;
rather a units implementation must register with the Registry converter
dictionary and provide a `ConversionInterface`. For example,
here is a complete implementation which supports plotting with native
datetime objects::
import matplotlib.units as units
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import datetime
class DateConverter(units.ConversionInterface):
@staticmethod
def convert(value, unit, axis):
"Convert a datetime value to a scalar or array."
return dates.date2num(value)
@staticmethod
def axisinfo(unit, axis):
"Return major and minor tick locators and formatters."
if unit != 'date':
return None
majloc = dates.AutoDateLocator()
majfmt = dates.AutoDateFormatter(majloc)
return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='date')
@staticmethod
def default_units(x, axis):
"Return the default unit for x or None."
return 'date'
# Finally we register our object type with the Matplotlib units registry.
units.registry[datetime.date] = DateConverter()
"""
from
decimal
import
Decimal
from
numbers
import
Number
import
numpy
as
np
from
numpy
import
ma
from
matplotlib
import
cbook
class
ConversionError
(
TypeError
):
pass
def
_is_natively_supported
(
x
):
"""
Return whether *x* is of a type that Matplotlib natively supports or an
array of objects of such types.
"""
# Matplotlib natively supports all number types except Decimal.
if
np
.
iterable
(
x
):
# Assume lists are homogeneous as other functions in unit system.
for
thisx
in
x
:
if
thisx
is
ma
.
masked
:
continue
return
isinstance
(
thisx
,
Number
)
and
not
isinstance
(
thisx
,
Decimal
)
else
:
return
isinstance
(
x
,
Number
)
and
not
isinstance
(
x
,
Decimal
)
class
AxisInfo
:
"""
Information to support default axis labeling, tick labeling, and limits.
An instance of this class must be returned by
`ConversionInterface.axisinfo`.
"""
def
__init__
(
self
,
majloc
=
None
,
minloc
=
None
,
majfmt
=
None
,
minfmt
=
None
,
label
=
None
,
default_limits
=
None
):
"""
Parameters
----------
majloc, minloc : Locator, optional
Tick locators for the major and minor ticks.
majfmt, minfmt : Formatter, optional
Tick formatters for the major and minor ticks.
label : str, optional
The default axis label.
default_limits : optional
The default min and max limits of the axis if no data has
been plotted.
Notes
-----
If any of the above are ``None``, the axis will simply use the
default value.
"""
self
.
majloc
=
majloc
self
.
minloc
=
minloc
self
.
majfmt
=
majfmt
self
.
minfmt
=
minfmt
self
.
label
=
label
self
.
default_limits
=
default_limits
class
ConversionInterface
:
"""
The minimal interface for a converter to take custom data types (or
sequences) and convert them to values Matplotlib can use.
"""
@
staticmethod
def
axisinfo
(
unit
,
axis
):
"""Return an `.AxisInfo` for the axis with the specified units."""
return
None
@
staticmethod
def
default_units
(
x
,
axis
):
"""Return the default unit for *x* or ``None`` for the given axis."""
return
None
@
staticmethod
def
convert
(
obj
,
unit
,
axis
):
"""
Convert *obj* using *unit* for the specified *axis*.
If *obj* is a sequence, return the converted sequence. The output must
be a sequence of scalars that can be used by the numpy array layer.
"""
return
obj
class
DecimalConverter
(
ConversionInterface
):
"""Converter for decimal.Decimal data to float."""
@
staticmethod
def
convert
(
value
,
unit
,
axis
):
"""
Convert Decimals to floats.
The *unit* and *axis* arguments are not used.
Parameters
----------
value : decimal.Decimal or iterable
Decimal or list of Decimal need to be converted
"""
if
isinstance
(
value
,
Decimal
):
return
float
(
value
)
# value is Iterable[Decimal]
elif
isinstance
(
value
,
ma
.
MaskedArray
):
return
ma
.
asarray
(
value
,
dtype
=
float
)
else
:
return
np
.
asarray
(
value
,
dtype
=
float
)
# axisinfo and default_units can be inherited as Decimals are Numbers.
class
Registry
(
dict
):
"""Register types with conversion interface."""
def
get_converter
(
self
,
x
):
"""Get the converter interface instance for *x*, or None."""
# Unpack in case of e.g. Pandas or xarray object
x
=
cbook
.
_unpack_to_numpy
(
x
)
if
isinstance
(
x
,
np
.
ndarray
):
# In case x in a masked array, access the underlying data (only its
# type matters). If x is a regular ndarray, getdata() just returns
# the array itself.
x
=
np
.
ma
.
getdata
(
x
).
ravel
()
# If there are no elements in x, infer the units from its dtype
if
not
x
.
size
:
return
self
.
get_converter
(
np
.
array
([
0
],
dtype
=
x
.
dtype
))
for
cls
in
type
(
x
).
__mro__
:
# Look up in the cache.
try
:
return
self
[
cls
]
except
KeyError
:
pass
try
:
# If cache lookup fails, look up based on first element...
first
=
cbook
.
_safe_first_finite
(
x
)
except
(
TypeError
,
StopIteration
):
pass
else
:
# ... and avoid infinite recursion for pathological iterables for
# which indexing returns instances of the same iterable class.
if
type
(
first
)
is
not
type
(
x
):
return
self
.
get_converter
(
first
)
return
None
registry
=
Registry
()
registry
[
Decimal
]
=
DecimalConverter
()
You can’t perform that action at this time.