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/scales/custom_scale.py at getmaskarray · oscargus/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 }}
oscargus
/
matplotlib
Public
forked from
matplotlib/matplotlib
Notifications
You must be signed in to change notification settings
Fork
1
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Files
Expand file tree
getmaskarray
Breadcrumbs
matplotlib
/
examples
/
scales
/
custom_scale.py
Copy path
Blame
More file actions
Blame
More file actions
Latest commit
History
History
History
169 lines (136 loc) · 6.23 KB
getmaskarray
Breadcrumbs
matplotlib
/
examples
/
scales
/
custom_scale.py
Copy path
Top
File metadata and controls
Code
Blame
169 lines (136 loc) · 6.23 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
"""
============
Custom scale
============
Create a custom scale, by implementing the scaling use for latitude data in a
Mercator Projection.
Unless you are making special use of the `.Transform` class, you probably
don't need to use this verbose method, and instead can use `~.scale.FuncScale`
and the ``'function'`` option of `~.Axes.set_xscale` and `~.Axes.set_yscale`.
See the last example in :doc:`/gallery/scales/scales`.
"""
import
numpy
as
np
from
numpy
import
ma
from
matplotlib
import
scale
as
mscale
from
matplotlib
import
transforms
as
mtransforms
from
matplotlib
.
ticker
import
FixedLocator
,
FuncFormatter
class
MercatorLatitudeScale
(
mscale
.
ScaleBase
):
"""
Scales data in range -pi/2 to pi/2 (-90 to 90 degrees) using
the system used to scale latitudes in a Mercator__ projection.
The scale function:
ln(tan(y) + sec(y))
The inverse scale function:
atan(sinh(y))
Since the Mercator scale tends to infinity at +/- 90 degrees,
there is user-defined threshold, above and below which nothing
will be plotted. This defaults to +/- 85 degrees.
__ https://en.wikipedia.org/wiki/Mercator_projection
"""
# The scale class must have a member ``name`` that defines the string used
# to select the scale. For example, ``ax.set_yscale("mercator")`` would be
# used to select this scale.
name
=
'mercator'
def
__init__
(
self
,
axis
,
*
,
thresh
=
np
.
deg2rad
(
85
),
**
kwargs
):
"""
Any keyword arguments passed to ``set_xscale`` and ``set_yscale`` will
be passed along to the scale's constructor.
thresh: The degree above which to crop the data.
"""
super
().
__init__
(
axis
)
if
thresh
>=
np
.
pi
/
2
:
raise
ValueError
(
"thresh must be less than pi/2"
)
self
.
thresh
=
thresh
def
get_transform
(
self
):
"""
Override this method to return a new instance that does the
actual transformation of the data.
The MercatorLatitudeTransform class is defined below as a
nested class of this one.
"""
return
self
.
MercatorLatitudeTransform
(
self
.
thresh
)
def
set_default_locators_and_formatters
(
self
,
axis
):
"""
Override to set up the locators and formatters to use with the
scale. This is only required if the scale requires custom
locators and formatters. Writing custom locators and
formatters is rather outside the scope of this example, but
there are many helpful examples in :mod:`.ticker`.
In our case, the Mercator example uses a fixed locator from -90 to 90
degrees and a custom formatter to convert the radians to degrees and
put a degree symbol after the value.
"""
fmt
=
FuncFormatter
(
lambda
x
,
pos
=
None
:
f"
{
np
.
degrees
(
x
):.0f
}
\N{DEGREE SIGN}
"
)
axis
.
set
(
major_locator
=
FixedLocator
(
np
.
radians
(
range
(
-
90
,
90
,
10
))),
major_formatter
=
fmt
,
minor_formatter
=
fmt
)
def
limit_range_for_scale
(
self
,
vmin
,
vmax
,
minpos
):
"""
Override to limit the bounds of the axis to the domain of the
transform. In the case of Mercator, the bounds should be
limited to the threshold that was passed in. Unlike the
autoscaling provided by the tick locators, this range limiting
will always be adhered to, whether the axis range is set
manually, determined automatically or changed through panning
and zooming.
"""
return
max
(
vmin
,
-
self
.
thresh
),
min
(
vmax
,
self
.
thresh
)
class
MercatorLatitudeTransform
(
mtransforms
.
Transform
):
# There are two value members that must be defined.
# ``input_dims`` and ``output_dims`` specify number of input
# dimensions and output dimensions to the transformation.
# These are used by the transformation framework to do some
# error checking and prevent incompatible transformations from
# being connected together. When defining transforms for a
# scale, which are, by definition, separable and have only one
# dimension, these members should always be set to 1.
input_dims
=
output_dims
=
1
def
__init__
(
self
,
thresh
):
mtransforms
.
Transform
.
__init__
(
self
)
self
.
thresh
=
thresh
def
transform_non_affine
(
self
,
a
):
"""
This transform takes a numpy array and returns a transformed copy.
Since the range of the Mercator scale is limited by the
user-specified threshold, the input array must be masked to
contain only valid values. Matplotlib will handle masked arrays
and remove the out-of-range data from the plot. However, the
returned array *must* have the same shape as the input array, since
these values need to remain synchronized with values in the other
dimension.
"""
masked
=
ma
.
masked_where
((
a
<
-
self
.
thresh
)
|
(
a
>
self
.
thresh
),
a
)
if
masked
.
mask
.
any
():
return
ma
.
log
(
np
.
abs
(
ma
.
tan
(
masked
)
+
1
/
ma
.
cos
(
masked
)))
else
:
return
np
.
log
(
np
.
abs
(
np
.
tan
(
a
)
+
1
/
np
.
cos
(
a
)))
def
inverted
(
self
):
"""
Override this method so Matplotlib knows how to get the
inverse transform for this transform.
"""
return
MercatorLatitudeScale
.
InvertedMercatorLatitudeTransform
(
self
.
thresh
)
class
InvertedMercatorLatitudeTransform
(
mtransforms
.
Transform
):
input_dims
=
output_dims
=
1
def
__init__
(
self
,
thresh
):
mtransforms
.
Transform
.
__init__
(
self
)
self
.
thresh
=
thresh
def
transform_non_affine
(
self
,
a
):
return
np
.
arctan
(
np
.
sinh
(
a
))
def
inverted
(
self
):
return
MercatorLatitudeScale
.
MercatorLatitudeTransform
(
self
.
thresh
)
# Now that the Scale class has been defined, it must be registered so
# that Matplotlib can find it.
mscale
.
register_scale
(
MercatorLatitudeScale
)
if
__name__
==
'__main__'
:
import
matplotlib
.
pyplot
as
plt
t
=
np
.
arange
(
-
180.0
,
180.0
,
0.1
)
s
=
np
.
radians
(
t
)
/
2.
plt
.
plot
(
t
,
s
,
'-'
,
lw
=
2
)
plt
.
yscale
(
'mercator'
)
plt
.
xlabel
(
'Longitude'
)
plt
.
ylabel
(
'Latitude'
)
plt
.
title
(
'Mercator projection'
)
plt
.
grid
(
True
)
plt
.
show
()
You can’t perform that action at this time.