Commit 54d00d37 authored by joakim kjellsson's avatar joakim kjellsson

added cmocean colormaps and fixed colorbar for single plots

parent cb9f148d
'''
cmocean is a package to help standardize colormaps for commonly-plotted
oceanographic properties.
See README.md for an overview on instructions.
'''
from __future__ import absolute_import
# from cmocean import *
from . import cm, tools, data
__all__ = ['cm',
'tools',
'plots',
'data']
__authors__ = ['Kristen Thyng <kthyng@tamu.edu>']
__version__ = "2.0"
'''
Standardized colormaps for oceanography plots.
Used tool from http://bids.github.io/colormap/ to make perceptually correct
colormaps.
Created by Kristen Thyng
2016-06-18
'''
from __future__ import absolute_import
import numpy as np
import os
from matplotlib import colors, cm
from . import tools
# Location of rgb files
datadir = os.path.join(os.path.split(__file__)[0], 'rgb')
# List of colormap names
cmapnames = ['thermal', 'haline', 'solar', 'ice', 'gray', 'oxy', 'deep',
'dense', 'algae', 'matter', 'turbid', 'speed', 'amp', 'tempo',
'rain', 'phase', 'topo', 'balance', 'delta', 'curl', 'diff', 'tarn']
# initialize dictionary to contain colormaps
cmap_d = dict()
# add colormaps and reversed to dictionary
for cmapname in cmapnames:
rgb = np.loadtxt(os.path.join(datadir, cmapname + '-rgb.txt'))
cmap_d[cmapname] = tools.cmap(rgb, N=256)
cmap_d[cmapname].name = cmapname
cmap_d[cmapname + '_r'] = tools.cmap(rgb[::-1, :], N=256)
cmap_d[cmapname + '_r'].name = cmapname + '_r'
# Register the cmap with matplotlib
rgb_with_alpha = np.zeros((rgb.shape[0],4))
rgb_with_alpha[:,:3] = rgb
rgb_with_alpha[:,3] = 1. #set alpha channel to 1
reg_map = colors.ListedColormap(rgb_with_alpha, 'cmo.' + cmapname, rgb.shape[0])
cm.register_cmap(cmap = reg_map)
# Register the reversed map
reg_map_r = colors.ListedColormap(rgb_with_alpha[::-1,:], 'cmo.' + cmapname + '_r', rgb.shape[0])
cm.register_cmap(cmap = reg_map_r)
# make colormaps available to call
locals().update(cmap_d)
File added
'''
All functions related to actual data go in here. Probably only
people at TAMU will want to use this.
'''
import numpy as np
import matplotlib.pyplot as plt
# data files
fnames = ['MS09_L10.mat.txt', 'MS09_L05.mat.txt',
'MS2_L10.mat.txt', 'MS08_L12.mat.txt']
def read(varin, fname='MS2_L10.mat.txt'):
'''Read in dataset for variable var
:param varin: Variable for which to read in data.
'''
# # fname = 'MS09_L10.mat.txt'
# # fname = 'MS09_L05.mat.txt' # has PAR
# fname = 'MS2_L10.mat.txt' # empty PAR
d = np.loadtxt(fname, comments='*')
if fname == 'MS2_L10.mat.txt':
var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen',
'voltage 2', 'voltage 3', 'fluorescence-CDOM', 'fluorescence-ECO',
'turbidity', 'pressure', 'salinity', 'RINKO temperature',
'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR']
elif (fname == 'MS09_L05.mat.txt') or (fname == 'MS09_L10.mat.txt') or (fname == 'MS08_L12.mat.txt'):
var = ['lat', 'lon', 'depth', 'temp', 'density', 'sigma', 'oxygen',
'voltage 2', 'voltage 3', 'voltage 4', 'fluorescence-CDOM', 'fluorescence-ECO',
'turbidity', 'pressure', 'salinity', 'RINKO temperature',
'RINKO DO - CTD temp', 'RINKO DO - RINKO temp', 'bottom', 'PAR']
# return data for variable varin
return d[:, 0], d[:, 1], d[:, 2], d[:, var.index(varin)]
def show(cmap, var, vmin=None, vmax=None):
'''Show a colormap for a chosen input variable var side by side with
black and white and jet colormaps.
:param cmap: Colormap instance
:param var: Variable to plot.
:param vmin=None: Min plot value.
:param vmax=None: Max plot value.
'''
# get variable data
lat, lon, z, data = read(var)
fig = plt.figure(figsize=(16, 12))
# Plot with grayscale
ax = fig.add_subplot(3, 1, 1)
map1 = ax.scatter(lon, -z, c=data, cmap='gray', s=10, linewidths=0., vmin=vmin, vmax=vmax)
plt.colorbar(map1, ax=ax)
# Plot with jet
ax = fig.add_subplot(3, 1, 2)
map1 = ax.scatter(lon, -z, c=data, cmap='jet', s=10, linewidths=0., vmin=vmin, vmax=vmax)
plt.colorbar(map1, ax=ax)
# Plot with cmap
ax = fig.add_subplot(3, 1, 3)
map1 = ax.scatter(lon, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=vmin, vmax=vmax)
ax.set_xlabel('Longitude [degrees]')
ax.set_ylabel('Depth [m]')
plt.colorbar(map1, ax=ax)
plt.suptitle(var)
def plot_data():
'''Plot sample data up with the fancy colormaps.
'''
var = ['temp', 'oxygen', 'salinity', 'fluorescence-ECO', 'density', 'PAR', 'turbidity', 'fluorescence-CDOM']
# colorbar limits for each property
lims = np.array([[26, 33], [0, 10], [0, 36], [0, 6], [1005, 1025], [0, 0.6], [0, 2], [0, 9]]) # reasonable values
# lims = np.array([[20,36], [26,33], [1.5,5.6], [0,4], [0,9], [0,1.5]]) # values to show colormaps
for fname in fnames:
fig, axes = plt.subplots(nrows=4, ncols=2)
fig.set_size_inches(20, 10)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99, wspace=0.0, hspace=0.07)
i = 0
for ax, Var, cmap in zip(axes.flat, var, cmaps): # loop through data to plot up
# get variable data
lat, lon, z, data = test.read(Var, fname)
map1 = ax.scatter(lat, -z, c=data, cmap=cmap, s=10, linewidths=0., vmin=lims[i, 0], vmax=lims[i, 1])
# no stupid offset
y_formatter = mpl.ticker.ScalarFormatter(useOffset=False)
ax.xaxis.set_major_formatter(y_formatter)
if i == 6:
ax.set_xlabel('Latitude [degrees]')
ax.set_ylabel('Depth [m]')
else:
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_ylim(-z.max(), 0)
ax.set_xlim(lat.min(), lat.max())
cb = plt.colorbar(map1, ax=ax, pad=0.02)
cb.set_label(cmap.name + ' [' + '$' + cmap.units + '$]')
i += 1
fig.savefig('figures/' + fname.split('.')[0] + '.png', bbox_inches='tight')
'''
Plots with colormaps.
'''
from __future__ import absolute_import
import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl
from . import cm
def plot_lightness(saveplot=False):
'''Plot lightness of colormaps together.
'''
from colorspacious import cspace_converter
dc = 1.
x = np.linspace(0.0, 1.0, 256)
locs = [] # locations for text labels
fig = plt.figure(figsize=(16, 5))
ax = fig.add_subplot(111)
fig.subplots_adjust(left=0.03, right=0.97)
ax.set_xlim(-0.1, len(cm.cmap_d)/2. + 0.1)
ax.set_ylim(0, 100)
ax.set_xlabel('Lightness for each colormap', fontsize=14)
for j, cmapname in enumerate(cm.cmapnames):
if '_r' in cmapname: # skip reversed versions for plot
continue
cmap = cm.cmap_d[cmapname] # get the colormap instance
rgb = cmap(x)[np.newaxis, :, :3]
lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
L = lab[0, :, 0]
if L[-1] > L[0]:
ax.scatter(x+j*dc, L, c=x, cmap=cmap, s=200, linewidths=0.)
else:
ax.scatter(x+j*dc, L[::-1], c=x[::-1], cmap=cmap, s=200, linewidths=0.)
locs.append(x[-1]+j*dc) # store locations for colormap labels
# Set up labels for colormaps
ax.xaxis.set_ticks_position('top')
ticker = mpl.ticker.FixedLocator(locs)
ax.xaxis.set_major_locator(ticker)
formatter = mpl.ticker.FixedFormatter([cmapname for cmapname in cm.cmapnames])
ax.xaxis.set_major_formatter(formatter)
labels = ax.get_xticklabels()
for label in labels:
label.set_rotation(60)
if saveplot:
fig.savefig('figures/lightness.png', bbox_inches='tight')
fig.savefig('figures/lightness.pdf', bbox_inches='tight')
plt.show()
def plot_gallery(saveplot=False):
'''Make plot of colormaps and labels, like in the matplotlib
gallery.
:param saveplot=False: Whether to save the plot or not.
'''
from colorspacious import cspace_converter
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
x = np.linspace(0.0, 1.0, 256)
fig, axes = plt.subplots(nrows=int(len(cm.cmap_d)/2), ncols=1, figsize=(6, 12))
fig.subplots_adjust(top=0.99, bottom=0.01, left=0.2, right=0.99, wspace=0.05)
for ax, cmapname in zip(axes, cm.cmapnames):
if '_r' in cmapname: # skip reversed versions for plot
continue
cmap = cm.cmap_d[cmapname] # get the colormap instance
rgb = cmap(x)[np.newaxis, :, :3]
# Find a good conversion to grayscale
jch = cspace_converter("sRGB1", "CAM02-UCS")(rgb) # Not sure why to use JCh instead so using this.
L = jch[0, :, 0]
L = np.float32(np.vstack((L, L, L)))
ax.imshow(gradient, aspect='auto', cmap=cmap)
pos1 = ax.get_position() # get the original position
pos2 = [pos1.x0, pos1.y0, pos1.width, pos1.height / 3.0]
axbw = fig.add_axes(pos2) # colorbar axes
axbw.set_axis_off()
axbw.imshow(L, aspect='auto', cmap=cm.gray, vmin=0, vmax=100.)
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, cmap.name, va='center', ha='right')
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
if saveplot:
fig.savefig('figures/gallery.pdf', bbox_inches='tight')
fig.savefig('figures/gallery.png', bbox_inches='tight')
plt.show()
def wrap_viscm(cmap, dpi=100, saveplot=False):
'''Evaluate goodness of colormap using perceptual deltas.
:param cmap: Colormap instance.
:param dpi=100: dpi for saved image.
:param saveplot=False: Whether to save the plot or not.
'''
from viscm import viscm
viscm(cmap)
fig = plt.gcf()
fig.set_size_inches(22, 10)
plt.show()
if saveplot:
fig.savefig('figures/eval_' + cmap.name + '.png', bbox_inches='tight', dpi=dpi)
fig.savefig('figures/eval_' + cmap.name + '.pdf', bbox_inches='tight', dpi=dpi)
def test(cmap, fig=None, ax=None):
'''Test colormap by plotting.
:param cmap: A colormap instance. Use a named one with cm.get_cmap(colormap)
'''
from colorspacious import cspace_converter
# indices to step through colormap
x = np.linspace(0.0, 1.0, 100)
# will plot colormap and lightness
rgb = cmap(x)[np.newaxis, :, :3]
lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, lab[0, :, 0], c=x, cmap=cmap, s=300, linewidths=0.)
ax.set_title(cmap.name, fontsize=14)
ax.set_ylabel('Lightness', fontsize=14)
ax.set_xticks([])
def quick_plot(cmap, fname=None, fig=None, ax=None, N=10):
'''Show quick test of a colormap.
'''
x = np.linspace(0, 10, N)
X, _ = np.meshgrid(x, x)
if ax is None:
fig = plt.figure()
ax = fig.add_subplot(111)
mappable = ax.pcolor(X, cmap=cmap)
ax.set_title(cmap.name, fontsize=14)
ax.set_xticks([])
ax.set_yticks([])
plt.colorbar(mappable)
plt.show()
if fname is not None:
plt.savefig(fname + '.png', bbox_inches='tight')
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment