8000 ENH: Added FuncNorm and PiecewiseNorm classes in colors by alvarosg · Pull Request #7294 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

ENH: Added FuncNorm and PiecewiseNorm classes in colors #7294

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 33 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
33 commits
Select commit Hold shift + click to select a range
2d90c5a
Added ArbitaryNorm and RootNorm classes in colors, as well as example…
Oct 17, 2016
57aad3d
PEP8 formatting on examples, plotting using the object oriented appro…
Oct 18, 2016
f818aff
Added title/description to the examples
Oct 18, 2016
ffe1b9d
Class attributes are now hidden
Oct 18, 2016
1d22b90
Major update: complete refactorization of code. A much more powerful …
Oct 19, 2016
b5801ea
Corrected lambda function syntax that was not compatible with python …
Oct 19, 2016
e93d82d
Added FuncNorm: now everything inherits from this. Changed the name o…
Oct 20, 2016
3749b0a
Forgot to uncomment an import
Oct 20, 2016
de62491
Improved the auto-tick feature, and corrected some pep8 issues
Oct 20, 2016
d148756
Improved examples, created a new file for generating sample data.'
alvarosg Oct 22, 2016
5373a98
Corrected a double line, and removed a comment
alvarosg Oct 22, 2016
13edeab
Tests for FuncNorm added, and bug corrected in FuncNorm
alvarosg Oct 22, 2016
21d5cd0
Added compatibility for python 3 string check, added tests for Piecew…
alvarosg Oct 22, 2016
d359a4e
Added tests on all classes, including all public methods
alvarosg Oct 22, 2016
4622829
Change type of arrays in tests from int to float
alvarosg Oct 22, 2016
30ff404
Corrected wrong `super()` for RootNorm
alvarosg Oct 22, 2016
df835cb
Solve problem with implicit int to float casting that was not working…
alvarosg Oct 22, 2016
dfaa0f8
Added documentation in the numpydoc format
alvarosg Oct 23, 2016
a386395
Improve style in the examples. Corrected intending problem in the doc…
alvarosg Oct 23, 2016
b9dafb0
Added example in `FuncNorm` docstring
alvarosg Oct 23, 2016
d10be73
Finished with the examples in the docstrings
alvarosg Oct 24, 2016
c85a14c
Implemented clipping behavoir. Refactored _func_parser
alvarosg Oct 26, 2016
7597ddd
It now allows some string functions with parameters. Added a test for…
alvarosg Oct 28, 2016
7fce503
Forgot to add a file...
alvarosg Oct 28, 2016
bcd7dd0
Forgot to add another file...
alvarosg Oct 28, 2016
a71e1e9
Improved tests, documentation, and exceptions
alvarosg Oct 31, 2016
33f57d1
Removed test_colors.py from __init__.py after including parametrize
alvarosg Oct 31, 2016
9687173
Moved the string function parser to its own class in cbook. Added tes…
alvarosg Nov 1, 2016
46395aa
Improved documentation
Nov 2, 2016
63dab61
Added new example
Nov 2, 2016
8abf2c2
Added example for PiecewiseNorm, and MirrorPiecewiseNorm. String in t…
alvarosg Nov 3, 2016
b4ecdb2
Removed sampledata.py no longer necessary, and changed examples in do…
alvarosg Nov 3, 2016
42007ee
Added examples for MirrorRootNorm and RootNorm
alvarosg Nov 3, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Added example for PiecewiseNorm, and MirrorPiecewiseNorm. String in t…
…he func_parser changed from crt to cbrt, to match common nomenclature
  • Loading branch information
alvarosg committed Nov 3, 2016
commit 8abf2c2bb193e311f0e693b4df4508a2ef359a8e
Original file line number Diff line number Diff line change
Expand Up @@ -20,36 +20,37 @@ def main():
fig, ((ax11, ax12),
(ax21, ax22),
(ax31, ax32)) = plt.subplots(3, 2, gridspec_kw={
'width_ratios': [1, 2]}, figsize=plt.figaspect(0.6))
'width_ratios': [1, 3.5]}, figsize=plt.figaspect(0.6))

cax = make_plot(None, 'Regular linear scale', fig, ax11, ax12)
fig.colorbar(cax, format='%.3g', ax=ax12)

# Example of logarithm normalization using FuncNorm
norm = colors.FuncNorm(f=np.log10,
finv=lambda x: 10.**(x), vmin=0.01)
cax = make_plot(norm, 'Log normalization using FuncNorm', fig, ax21, ax22)
cax = make_plot(norm, 'Log normalization', fig, ax21, ax22)
fig.colorbar(cax, format='%.3g', ticks=cax.norm.ticks(5), ax=ax22)
# The same can be achieved with
# norm = colors.FuncNorm(f='log10', vmin=0.01)

# Example of root normalization using FuncNorm
norm = colors.FuncNorm(f=lambda x: x**0.5,
finv=lambda x: x**2, vmin=0.0)
cax = make_plot(norm, 'Root normalization using FuncNorm', fig, ax31, ax32)
cax = make_plot(norm, 'Root normalization', fig, ax31, ax32)
fig.colorbar(cax, format='%.3g', ticks=cax.norm.ticks(5), ax=ax32)
# The same can be achieved with
# norm = colors.FuncNorm(f='sqrt', vmin=0.0)
# or with
# norm = colors.FuncNorm(f='root{2}', vmin=0.)

fig.subplots_adjust(hspace=0.4, wspace=0.15)
fig.suptitle('Normalization with FuncNorm')
plt.show()


def make_plot(norm, label, fig, ax1, ax2):
X, Y, data = get_data()
cax = ax2.imshow(data, cmap=cm.gray, norm=norm)
cax = ax2.imshow(data, cmap=cm.afmhot, norm=norm)

d_values = np.linspace(cax.norm.vmin, cax.norm.vmax, 100)
cm_values = cax.norm(d_values)
Expand All @@ -75,7 +76,7 @@ def gauss2d(x, y, a0, x0, y0, wx, wy):
return a0 * np.exp(-(x - x0)**2 / wx**2 - (y - y0)**2 / wy**2)
N = 15
for x in np.linspace(0., 1, N):
data += gauss2d(X, Y, x, x, 0, 0.25/N, 0.25)
data += gauss2d(X, Y, x, x, 0, 0.25 / N, 0.25)

data = data - data.min()
data = data / data.max()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
"""
================================================================================
Examples of normalization using :class:`~matplotlib.colors.MirrorPiecewiseNorm`
================================================================================

This is an example on how to perform a normalization for positive
and negative data around zero independently using
class:`~matplotlib.colors.MirrorPiecewiseNorm`.

"""

import matplotlib.cm as cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt

import numpy as np


def main():
fig, ((ax11, ax12),
(ax21, ax22),
(ax31, ax32)) = plt.subplots(3, 2, gridspec_kw={
'width_ratios': [1, 3.5]}, figsize=plt.figaspect(0.6))

cax = make_plot(None, 'Regular linear scale', fig, ax11, ax12)
fig.colorbar(cax, format='%.3g', ax=ax12)

# Example of symmetric root normalization using MirrorPiecewiseNorm
norm = colors.MirrorPiecewiseNorm(fpos=lambda x: x**(1 / 3.),
fposinv=lambda x: x**3)
cax = make_plot(norm, 'Symmetric cubic root normalization around zero',
fig, ax21, ax22)
fig.colorbar(cax, format='%.3g', ticks=cax.norm.ticks(5), ax=ax22)
# The same can be achieved with
# norm = colors.MirrorPiecewiseNorm(fpos='cbrt')
# or with
# norm = colors.MirrorPiecewiseNorm(fpos='root{3}')

# Example of asymmetric root normalization using MirrorPiecewiseNorm
norm = colors.MirrorPiecewiseNorm(fpos=lambda x: x**(1 / 3.),
fposinv=lambda x: x**3,
fneg=lambda x: x,
fneginv=lambda x: x)
cax = make_plot(norm, 'Cubic root normalization above zero\n'
'and linear below zero',
fig, ax31, ax32)
fig.colorbar(cax, format='%.3g', ticks=cax.norm.ticks(5), ax=ax32)
# The same can be achieved with
# norm = colors.MirrorPiecewiseNorm(fpos='cbrt', fneg='linear')
# or with
# norm = colors.MirrorPiecewiseNorm(fpos='root{3}', fneg='linear')

fig.subplots_adjust(hspace=0.4, wspace=0.15)
fig.suptitle('Normalization with MirrorPiecewiseNorm')
plt.show()


def make_plot(norm, label, fig, ax1, ax2):
X, Y, data = get_data()
cax = ax2.imshow(data, cmap=cm.seismic, norm=norm)

d_values = np.linspace(cax.norm.vmin, cax.norm.vmax, 100)
cm_values = cax.norm(d_values)
ax1.plot(d_values, cm_values)
ax1.set_xlabel('Data values')
ax1.set_ylabel('Colormap values')
ax2.set_title(label)
ax2.axes.get_xaxis().set_ticks([])
ax2.axes.get_yaxis().set_ticks([])
return cax


def get_data(_cache=[]):
if len(_cache) > 0:
return _cache[0]
x = np.linspace(0, 1, 300)
y = np.linspace(-1, 1, 90)
X, Y = np.meshgrid(x, y)

data = np.zeros(X.shape)

def gauss2d(x, y, a0, x0, y0, wx, wy):
return a0 * np.exp(-(x - x0)**2 / wx**2 - (y - y0)**2 / wy**2)
N = 15
for x in np.linspace(0., 1, N):
data += gauss2d(X, Y, x, x, -0.5, 0.25 / N, 0.15)
data -= gauss2d(X, Y, x, x, 0.5, 0.25 / N, 0.15)

data[data > 0] = data[data > 0] / data.max()
data[data < 0] = data[data < 0] / -data.min()
_cache.append((X, Y, data))

return _cache[0]

main()
Original file line number Diff line number Diff line change
@@ -1,103 +1,93 @@
"""
============================================
Examples of arbitrary colormap normalization
============================================
=========================================================================
Examples of normalization using :class:`~matplotlib.colors.PiecewiseNorm`
=========================================================================

Here I plot an image array with data spanning for a large dynamic range,
using different normalizations. Look at how each of them enhances
different features.
This is an example on how to perform a normalization defined by intervals
using class:`~matplotlib.colors.PiecewiseNorm`.

"""


import matplotlib.cm as cm
import matplotlib.colors as colors
import matplotlib.pyplot as plt

from mpl_toolkits.mplot3d import Axes3D

import numpy as np

from sampledata import PiecewiseNormData

X, Y, data = PiecewiseNormData()
cmap = cm.spectral
def main():
fig, ((ax11, ax12),
(ax21, ax22)) = plt.subplots(2, 2, gridspec_kw={
'width_ratios': [1, 3]}, figsize=plt.figaspect(0.6))

cax = make_plot(None, 'Regular linear scale', fig, ax11, ax12)
fig.colorbar(cax, format='%.3g', ax=ax12)

# Example of amplification of features above 0.2 and 0.6
norm = colors.PiecewiseNorm(flist=['linear', 'root{4}', 'linear',
'root{4}', 'linear'],
refpoints_cm=[0.2, 0.4, 0.6, 0.8],
refpoints_data=[0.2, 0.4, 0.6, 0.8])
cax = make_plot(norm, 'Amplification of features above 0.2 and 0.6',
fig, ax21, ax22)
fig.colorbar(cax, format='%.3g', ticks=cax.norm.ticks(11), ax=ax22)
# The same can be achieved with
# norm = colors.PiecewiseNorm(flist=[lambda x: x,
# lambda x: x**(1. / 4),
# lambda x: x,
# lambda x: x**(1. / 4),
# lambda x: x],
# finvlist=[lambda x: x,
# lambda x: x**4,
# lambda x: x,
# lambda x: x**4,
# lambda x: x],
# refpoints_cm=[0.2, 0.4, 0.6, 0.8],
# refpoints_data=[0.2, 0.4, 0.6, 0.8])

fig.subplots_adjust(hspace=0.4, wspace=0.15)
fig.suptitle('Normalization with PiecewiseNorm')
plt.show()


def make_plot(norm, label, fig, ax1, ax2):
X, Y, data = get_data()
cax = ax2.imshow(data, cmap=cm.gist_heat, norm=norm)

d_values = np.linspace(cax.norm.vmin, cax.norm.vmax, 300)
cm_values = cax.norm(d_values)
ax1.plot(d_values, cm_values)
ax1.set_xlabel('Data values')
ax1.set_ylabel('Colormap values')
ax2.set_title(label)
ax2.axes.get_xaxis().set_ticks([])
ax2.axes.get_yaxis().set_ticks([])
return cax

# Creating functions for plotting

def get_data(_cache=[]):
if len(_cache) > 0:
return _cache[0]
x = np.linspace(0, 1, 301)[:-1]
y = np.linspace(-1, 1, 120)
X, Y = np.meshgrid(x, y)

def make_plot(norm, label=''):
fig, (ax1, ax2) = plt.subplots(1, 2, gridspec_kw={
'width_ratios': [1, 2]}, figsize=plt.figaspect(0.5))
fig.subplots_adjust(top=0.87, left=0.07, right=0.96)
fig.suptitle(label)
data = np.zeros(X.shape)

cax = ax2.pcolormesh(X, Y, data, cmap=cmap, norm=norm)
ticks = cax.norm.ticks() if norm else None
fig.colorbar(cax, format='%.3g', ticks=ticks)
ax2.set_xlim(X.min(), X.max())
ax2.set_ylim(Y.min(), Y.max())
def supergauss2d(o, x, y, a0, x0, y0, wx, wy):
x_ax = ((x - x0) / wx)**2
y_ax = ((y - y0) / wy)**2
return a0 * np.exp(-(x_ax + y_ax)**o)
N = 6

data_values = np.linspace(cax.norm.vmin, cax.norm.vmax, 100)
cm_values = cax.norm(data_values)
ax1.plot(data_values, cm_values)
ax1.set_xlabel('Data values')
ax1.set_ylabel('Colormap values')
data += np.floor(X * (N)) / (N - 1)

for x in np.linspace(0., 1, N + 1)[0:-1]:
data += supergauss2d(3, X, Y, 0.05, x + 0.5 / N, -0.5, 0.25 / N, 0.15)
data -= supergauss2d(3, X, Y, 0.05, x + 0.5 / N, 0.5, 0.25 / N, 0.15)

data = np.clip(data, 0, 1)
_cache.append((X, Y, data))
return _cache[0]

def make_3dplot(label=''):
fig = plt.figure()
fig.suptitle(label)
ax = fig.gca(projection='3d')
cax = ax.plot_surface(X, Y, data, rstride=1, cstride=1,
cmap=cmap, linewidth=0, antialiased=False)
ax.set_zlim(data.min(), data.max())
fig.colorbar(cax, shrink=0.5, aspect=5)
ax.view_init(20, 225)


# Showing how the data looks in linear scale
make_3dplot('Regular linear scale')
make_plot(None, 'Regular linear scale')

# Example of logarithm normalization using FuncNorm
norm = colors.FuncNorm(f=lambda x: np.log10(x),
finv=lambda x: 10.**(x), vmin=0.01, vmax=2)
make_plot(norm, "Log normalization using FuncNorm")
# The same can be achived with
# norm = colors.FuncNorm(f='log10', vmin=0.01, vmax=2)

# Example of root normalization using FuncNorm
norm = colors.FuncNorm(f='sqrt', vmin=0.0, vmax=2)
make_plot(norm, "Root normalization using FuncNorm")

# Performing a symmetric amplification of the features around 0
norm = colors.MirrorPiecewiseNorm(fpos='crt')
make_plot(norm, "Amplified features symetrically around \n"
"0 with MirrorPiecewiseNorm")


# Amplifying features near 0.6 with MirrorPiecewiseNorm
norm = colors.MirrorPiecewiseNorm(fpos='crt', fneg='crt',
center_cm=0.35,
center_data=0.6)
make_plot(norm, "Amplifying positive and negative features\n"
"standing on 0.6 with MirrorPiecewiseNorm")

# Amplifying features near both -0.4 and near 1.2 with PiecewiseNorm
norm = colors.PiecewiseNorm(flist=['cubic', 'crt', 'cubic', 'crt'],
refpoints_cm=[0.25, 0.5, 0.75],
refpoints_data=[-0.4, 1, 1.2])
make_plot(norm, "Amplifying positive and negative features standing\n"
" on -0.4 and 1.2 with PiecewiseNorm")

# Amplifying positive features near -1, -0.2 and 1.2 simultaneously with
# PiecewiseNorm
norm = colors.PiecewiseNorm(flist=['crt', 'crt', 'crt'],
refpoints_cm=[0.4, 0.7],
refpoints_data=[-0.2, 1.2])
make_plot(norm, "Amplifying only positive features standing on -1, -0.2\n"
" and 1.2 with PiecewiseNorm")


plt.show()
main()
2 changes: 1 addition & 1 deletion lib/matplotlib/cbook.py
8000
Original file line number Diff line number Diff line change
Expand Up @@ -2709,7 +2709,7 @@ class _StringFuncParser(object):
'quadratic': (lambda x: x**2, lambda x: x**(1. / 2), True),
'cubic': (lambda x: x**3, lambda x: x**(1. / 3), True),
'sqrt': (lambda x: x**(1. / 2), lambda x: x**2, True),
'crt': (lambda x: x**(1. / 3), lambda x: x**3, True),
'cbrt': (lambda x: x**(1. / 3), lambda x: x**3, True),
'log10': (lambda x: np.log10(x), lambda x: (10**(x)), False),
'log': (lambda x: np.log(x), lambda x: (np.exp(x)), False),
'power{a}': (lambda x, a: x**a,
Expand Down
12 changes: 6 additions & 6 deletions lib/matplotlib/colors.py
Original file line number Diff line number Diff line change
Expand Up @@ -978,7 +978,7 @@ def __init__(self, f, finv=None, **normalize_kw):
Function to be used for the normalization receiving a single
parameter, compatible with scalar values and ndarrays.
Alternatively a string from the list ['linear', 'quadratic',
'cubic', 'sqrt', 'crt','log', 'log10', 'power{a}', 'root{a}',
'cubic', 'sqrt', 'cbrt','log', 'log10', 'power{a}', 'root{a}',
'log(x+{a})', 'log10(x+{a})'] can be used, replacing 'a' by a
number different than 0 when necessary.
finv : callable, optional
Expand Down Expand Up @@ -1236,7 +1236,7 @@ def __init__(self, flist,
1.2 using four intervals:

>>> import matplotlib.colors as colors
>>> norm = colors.PiecewiseNorm(flist=['cubic', 'crt', 'cubic', 'crt'],
>>> norm = colors.PiecewiseNorm(flist=['cubic', 'cbrt', 'cubic', 'cbrt'],
>>> refpoints_cm=[0.25, 0.5, 0.75],
>>> refpoints_data=[-0.4, 1, 1.2])

Expand Down Expand Up @@ -1496,12 +1496,12 @@ def __init__(self,
Obtaining a symmetric amplification of the features around 0:

>>> import matplotlib.colors as colors
>>> norm = colors.MirrorPiecewiseNorm(fpos='crt'):
>>> norm = colors.MirrorPiecewiseNorm(fpos='cbrt'):

Obtaining an asymmetric amplification of the features around 0.6:

>>> import matplotlib.colors as colors
>>> norm = colors.MirrorPiecewiseNorm(fpos='sqrt', fneg='crt',
>>> norm = colors.MirrorPiecewiseNorm(fpos='sqrt', fneg='cbrt',
>>> center_cm=0.35,
>>> center_data=0.6)

Expand Down Expand Up @@ -1582,7 +1582,7 @@ class MirrorRootNorm(MirrorPiecewiseNorm):
to `colors.MirrorPiecewiseNorm(fpos='sqrt')`

`colors.MirrorRootNorm(orderpos=2, orderneg=3)` is equivalent
to `colors.MirrorPiecewiseNorm(fpos='sqrt', fneg='crt')`
to `colors.MirrorPiecewiseNorm(fpos='sqrt', fneg='cbrt')`

`colors.MirrorRootNorm(orderpos=N1, orderneg=N2)` is equivalent
to `colors.MirrorPiecewiseNorm(fpos=root{N1}', fneg=root{N2}')`
Expand Down Expand Up @@ -1652,7 +1652,7 @@ class RootNorm(FuncNorm):

`colors.RootNorm(order=2)` is equivalent to `colors.FuncNorm(f='sqrt')`

`colors.RootNorm(order=3)` is equivalent to `colors.FuncNorm(f='crt')`
`colors.RootNorm(order=3)` is equivalent to `colors.FuncNorm(f='cbrt')`

`colors.RootNorm(order=N)` is equivalent to `colors.FuncNorm(f='root{N}')`

Expand Down
2 changes: 1 addition & 1 deletion lib/matplotlib/tests/test_cbook.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,7 +525,7 @@ def test_flatiter():

class TestFuncParser(object):
x_test = np.linspace(0.01, 0.5, 3)
validstrings = ['linear', 'quadratic', 'cubic', 'sqrt', 'crt',
validstrings = ['linear', 'quadratic', 'cubic', 'sqrt', 'cbrt',
'log', 'log10', 'power{1.5}', 'root{2.5}',
'log(x+{0.5})', 'log10(x+{0.1})']
results = [(lambda x: x),
Expand Down
Loading
0