[plotting] restructuring more and more

This commit is contained in:
mzwiessele 2015-10-04 12:31:22 +01:00
parent c07f3dbe98
commit 831e032ade
18 changed files with 330 additions and 272 deletions

View file

@ -1,166 +0,0 @@
# Copyright (c) 2012, GPy authors (see AUTHORS.txt).
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import matplotlib as mpl
from matplotlib import pyplot as pb
import sys
#sys.path.append('/home/james/mlprojects/sitran_cluster/')
#from switch_pylab_backend import *
#this stuff isn;t really Tango related: maybe it could be moved out? TODO
def removeRightTicks(ax=None):
ax = ax or pb.gca()
for i, line in enumerate(ax.get_yticklines()):
if i%2 == 1: # odd indices
line.set_visible(False)
def removeUpperTicks(ax=None):
ax = ax or pb.gca()
for i, line in enumerate(ax.get_xticklines()):
if i%2 == 1: # odd indices
line.set_visible(False)
def fewerXticks(ax=None,divideby=2):
ax = ax or pb.gca()
ax.set_xticks(ax.get_xticks()[::divideby])
colorsHex = {\
"Aluminium6":"#2e3436",\
"Aluminium5":"#555753",\
"Aluminium4":"#888a85",\
"Aluminium3":"#babdb6",\
"Aluminium2":"#d3d7cf",\
"Aluminium1":"#eeeeec",\
"lightPurple":"#ad7fa8",\
"mediumPurple":"#75507b",\
"darkPurple":"#5c3566",\
"lightBlue":"#729fcf",\
"mediumBlue":"#3465a4",\
"darkBlue": "#204a87",\
"lightGreen":"#8ae234",\
"mediumGreen":"#73d216",\
"darkGreen":"#4e9a06",\
"lightChocolate":"#e9b96e",\
"mediumChocolate":"#c17d11",\
"darkChocolate":"#8f5902",\
"lightRed":"#ef2929",\
"mediumRed":"#cc0000",\
"darkRed":"#a40000",\
"lightOrange":"#fcaf3e",\
"mediumOrange":"#f57900",\
"darkOrange":"#ce5c00",\
"lightButter":"#fce94f",\
"mediumButter":"#edd400",\
"darkButter":"#c4a000"}
darkList = [colorsHex['darkBlue'],colorsHex['darkRed'],colorsHex['darkGreen'], colorsHex['darkOrange'], colorsHex['darkButter'], colorsHex['darkPurple'], colorsHex['darkChocolate'], colorsHex['Aluminium6']]
mediumList = [colorsHex['mediumBlue'], colorsHex['mediumRed'],colorsHex['mediumGreen'], colorsHex['mediumOrange'], colorsHex['mediumButter'], colorsHex['mediumPurple'], colorsHex['mediumChocolate'], colorsHex['Aluminium5']]
lightList = [colorsHex['lightBlue'], colorsHex['lightRed'],colorsHex['lightGreen'], colorsHex['lightOrange'], colorsHex['lightButter'], colorsHex['lightPurple'], colorsHex['lightChocolate'], colorsHex['Aluminium4']]
def currentDark():
return darkList[-1]
def currentMedium():
return mediumList[-1]
def currentLight():
return lightList[-1]
def nextDark():
darkList.append(darkList.pop(0))
return darkList[-1]
def nextMedium():
mediumList.append(mediumList.pop(0))
return mediumList[-1]
def nextLight():
lightList.append(lightList.pop(0))
return lightList[-1]
def reset():
while not darkList[0]==colorsHex['darkBlue']:
darkList.append(darkList.pop(0))
while not mediumList[0]==colorsHex['mediumBlue']:
mediumList.append(mediumList.pop(0))
while not lightList[0]==colorsHex['lightBlue']:
lightList.append(lightList.pop(0))
def setLightFigures():
mpl.rcParams['axes.edgecolor']=colorsHex['Aluminium6']
mpl.rcParams['axes.facecolor']=colorsHex['Aluminium2']
mpl.rcParams['axes.labelcolor']=colorsHex['Aluminium6']
mpl.rcParams['figure.edgecolor']=colorsHex['Aluminium6']
mpl.rcParams['figure.facecolor']=colorsHex['Aluminium2']
mpl.rcParams['grid.color']=colorsHex['Aluminium6']
mpl.rcParams['savefig.edgecolor']=colorsHex['Aluminium2']
mpl.rcParams['savefig.facecolor']=colorsHex['Aluminium2']
mpl.rcParams['text.color']=colorsHex['Aluminium6']
mpl.rcParams['xtick.color']=colorsHex['Aluminium6']
mpl.rcParams['ytick.color']=colorsHex['Aluminium6']
def setDarkFigures():
mpl.rcParams['axes.edgecolor']=colorsHex['Aluminium2']
mpl.rcParams['axes.facecolor']=colorsHex['Aluminium6']
mpl.rcParams['axes.labelcolor']=colorsHex['Aluminium2']
mpl.rcParams['figure.edgecolor']=colorsHex['Aluminium2']
mpl.rcParams['figure.facecolor']=colorsHex['Aluminium6']
mpl.rcParams['grid.color']=colorsHex['Aluminium2']
mpl.rcParams['savefig.edgecolor']=colorsHex['Aluminium6']
mpl.rcParams['savefig.facecolor']=colorsHex['Aluminium6']
mpl.rcParams['text.color']=colorsHex['Aluminium2']
mpl.rcParams['xtick.color']=colorsHex['Aluminium2']
mpl.rcParams['ytick.color']=colorsHex['Aluminium2']
def hex2rgb(hexcolor):
hexcolor = [hexcolor[1+2*i:1+2*(i+1)] for i in range(3)]
r,g,b = [int(n,16) for n in hexcolor]
return (r,g,b)
colorsRGB = dict([(k,hex2rgb(i)) for k,i in colorsHex.items()])
cdict_RB = {'red' :((0.,colorsRGB['mediumRed'][0]/256.,colorsRGB['mediumRed'][0]/256.),
(.5,colorsRGB['mediumPurple'][0]/256.,colorsRGB['mediumPurple'][0]/256.),
(1.,colorsRGB['mediumBlue'][0]/256.,colorsRGB['mediumBlue'][0]/256.)),
'green':((0.,colorsRGB['mediumRed'][1]/256.,colorsRGB['mediumRed'][1]/256.),
(.5,colorsRGB['mediumPurple'][1]/256.,colorsRGB['mediumPurple'][1]/256.),
(1.,colorsRGB['mediumBlue'][1]/256.,colorsRGB['mediumBlue'][1]/256.)),
'blue':((0.,colorsRGB['mediumRed'][2]/256.,colorsRGB['mediumRed'][2]/256.),
(.5,colorsRGB['mediumPurple'][2]/256.,colorsRGB['mediumPurple'][2]/256.),
(1.,colorsRGB['mediumBlue'][2]/256.,colorsRGB['mediumBlue'][2]/256.))}
cdict_BGR = {'red' :((0.,colorsRGB['mediumBlue'][0]/256.,colorsRGB['mediumBlue'][0]/256.),
(.5,colorsRGB['mediumGreen'][0]/256.,colorsRGB['mediumGreen'][0]/256.),
(1.,colorsRGB['mediumRed'][0]/256.,colorsRGB['mediumRed'][0]/256.)),
'green':((0.,colorsRGB['mediumBlue'][1]/256.,colorsRGB['mediumBlue'][1]/256.),
(.5,colorsRGB['mediumGreen'][1]/256.,colorsRGB['mediumGreen'][1]/256.),
(1.,colorsRGB['mediumRed'][1]/256.,colorsRGB['mediumRed'][1]/256.)),
'blue':((0.,colorsRGB['mediumBlue'][2]/256.,colorsRGB['mediumBlue'][2]/256.),
(.5,colorsRGB['mediumGreen'][2]/256.,colorsRGB['mediumGreen'][2]/256.),
(1.,colorsRGB['mediumRed'][2]/256.,colorsRGB['mediumRed'][2]/256.))}
cdict_Alu = {'red' :((0./5,colorsRGB['Aluminium1'][0]/256.,colorsRGB['Aluminium1'][0]/256.),
(1./5,colorsRGB['Aluminium2'][0]/256.,colorsRGB['Aluminium2'][0]/256.),
(2./5,colorsRGB['Aluminium3'][0]/256.,colorsRGB['Aluminium3'][0]/256.),
(3./5,colorsRGB['Aluminium4'][0]/256.,colorsRGB['Aluminium4'][0]/256.),
(4./5,colorsRGB['Aluminium5'][0]/256.,colorsRGB['Aluminium5'][0]/256.),
(5./5,colorsRGB['Aluminium6'][0]/256.,colorsRGB['Aluminium6'][0]/256.)),
'green' :((0./5,colorsRGB['Aluminium1'][1]/256.,colorsRGB['Aluminium1'][1]/256.),
(1./5,colorsRGB['Aluminium2'][1]/256.,colorsRGB['Aluminium2'][1]/256.),
(2./5,colorsRGB['Aluminium3'][1]/256.,colorsRGB['Aluminium3'][1]/256.),
(3./5,colorsRGB['Aluminium4'][1]/256.,colorsRGB['Aluminium4'][1]/256.),
(4./5,colorsRGB['Aluminium5'][1]/256.,colorsRGB['Aluminium5'][1]/256.),
(5./5,colorsRGB['Aluminium6'][1]/256.,colorsRGB['Aluminium6'][1]/256.)),
'blue' :((0./5,colorsRGB['Aluminium1'][2]/256.,colorsRGB['Aluminium1'][2]/256.),
(1./5,colorsRGB['Aluminium2'][2]/256.,colorsRGB['Aluminium2'][2]/256.),
(2./5,colorsRGB['Aluminium3'][2]/256.,colorsRGB['Aluminium3'][2]/256.),
(3./5,colorsRGB['Aluminium4'][2]/256.,colorsRGB['Aluminium4'][2]/256.),
(4./5,colorsRGB['Aluminium5'][2]/256.,colorsRGB['Aluminium5'][2]/256.),
(5./5,colorsRGB['Aluminium6'][2]/256.,colorsRGB['Aluminium6'][2]/256.))}
# cmap_Alu = mpl.colors.LinearSegmentedColormap('TangoAluminium',cdict_Alu,256)
# cmap_BGR = mpl.colors.LinearSegmentedColormap('TangoRedBlue',cdict_BGR,256)
# cmap_RB = mpl.colors.LinearSegmentedColormap('TangoRedBlue',cdict_RB,256)
if __name__=='__main__':
from matplotlib import pyplot as pb
pb.figure()
pb.pcolor(pb.rand(10,10),cmap=cmap_RB)
pb.colorbar()
pb.show()

View file

@ -8,7 +8,7 @@ from . import variational_plots
from . import kernel_plots
from . import dim_reduction_plots
from . import mapping_plots
from . import Tango
from GPy.plotting.gpy_plot import Tango
from . import visualize
from . import latent_space_visualizations
from . import inference_plots

View file

@ -30,7 +30,7 @@
from matplotlib.colors import LinearSegmentedColormap
from matplotlib import cm
from . import Tango
from GPy.plotting.gpy_plot import Tango
'''
This file is for defaults for the gpy plot, specific to the plotting library.
@ -43,17 +43,24 @@ In the code, always ise plotting.gpy_plots.defaults to get the defaults, as
it gives back an empty default, when defaults are not defined.
'''
# Data:
# Data plots:
data_1d = dict(lw=1.5, marker='x', edgecolor='k')
data_2d = dict(s=35, edgecolors='none', linewidth=0., cmap=cm.get_cmap('hot'), alpha=.5)
inducing_1d = dict(lw=0, s=500, facecolors=Tango.colorsHex['darkRed'])
inducing_2d = dict(s=14, edgecolors='k', linewidth=.4, facecolors='white', alpha=.5)
xerrorbar = dict(ecolor='k', fmt='none', elinewidth=.5, alpha=.5)
yerrorbar = dict(ecolor=Tango.colorsHex['darkRed'], fmt='none', elinewidth=.5, alpha=.5)
xerrorbar = dict(color='k', fmt='none', elinewidth=.5, alpha=.5)
yerrorbar = dict(color=Tango.colorsHex['darkRed'], fmt='none', elinewidth=.5, alpha=.5)
# GP plots
# GP plots:
meanplot_1d = dict(color=Tango.colorsHex['mediumBlue'], linewidth=2)
meanplot_2d = dict(cmap='hot', linewidth=.5)
samples_1d = dict(color=Tango.colorsHex['mediumBlue'], linewidth=.3)
confidence_interval = dict(edgecolor=Tango.colorsHex['darkBlue'],linewidth=.5,facecolor=Tango.colorsHex['lightBlue'],alpha=.2)
density = dict(alpha=.5, facecolor=Tango.colorsHex['mediumBlue'], edgecolors='none')
confidence_interval = dict(edgecolor=Tango.colorsHex['darkBlue'], linewidth=.5, color=Tango.colorsHex['lightBlue'],alpha=.2)
density = dict(alpha=.5, color=Tango.colorsHex['mediumBlue'])
# GPLVM plots:
data_y_1d = dict(linewidth=0, cmap='RdBu', s=40)
data_y_1d_plot = dict(color='k', linewidth=1.5)
# Kernel plots:
ard = dict(edgecolor='k', linewidth=1.2)

View file

@ -7,31 +7,13 @@ from ...core.parameterization.variational import VariationalPosterior
from .base_plots import x_frame2D
import itertools
try:
from . import Tango
from GPy.plotting.gpy_plot import Tango
from matplotlib.cm import get_cmap
from matplotlib import pyplot as pb
from matplotlib import cm
except:
pass
def most_significant_input_dimensions(model, which_indices):
"""
Determine which dimensions should be plotted
"""
if which_indices is None:
if model.input_dim == 1:
input_1 = 0
input_2 = None
if model.input_dim == 2:
input_1, input_2 = 0, 1
else:
try:
input_1, input_2 = np.argsort(model.input_sensitivity())[::-1][:2]
except:
raise ValueError("cannot automatically determine which dimensions to plot, please pass 'which_indices'")
else:
input_1, input_2 = which_indices
return input_1, input_2
def plot_latent(model, labels=None, which_indices=None,
resolution=50, ax=None, marker='o', s=40,
@ -52,7 +34,7 @@ def plot_latent(model, labels=None, which_indices=None,
if labels is None:
labels = np.ones(model.num_data)
input_1, input_2 = most_significant_input_dimensions(model, which_indices)
input_1, input_2 = model.get_most_significant_input_dimensions(which_indices)
#fethch the data points X that we'd like to plot
X = model.X
@ -219,7 +201,7 @@ def plot_magnification(model, labels=None, which_indices=None,
if labels is None:
labels = np.ones(model.num_data)
input_1, input_2 = most_significant_input_dimensions(model, which_indices)
input_1, input_2 = model.get_most_significant_input_dimensions(which_indices)
#fethch the data points X that we'd like to plot
X = model.X
@ -366,7 +348,7 @@ def plot_magnification(model, labels=None, which_indices=None,
def plot_steepest_gradient_map(model, fignum=None, ax=None, which_indices=None, labels=None, data_labels=None, data_marker='o', data_s=40, resolution=20, aspect='auto', updates=False, ** kwargs):
input_1, input_2 = significant_dims = most_significant_input_dimensions(model, which_indices)
input_1, input_2 = significant_dims = model.get_most_significant_input_dimensions(which_indices)
X = np.zeros((resolution ** 2, model.input_dim))
indices = np.r_[:X.shape[0]]

View file

@ -3,13 +3,10 @@
import numpy as np
from matplotlib import pyplot as pb
from . import Tango
from matplotlib.textpath import TextPath
from matplotlib.transforms import offset_copy
from .base_plots import ax_default
def add_bar_labels(fig, ax, bars, bottom=0):
transOffset = offset_copy(ax.transData, fig=fig,
x=0., y= -2., units='points')
@ -40,63 +37,6 @@ def plot_bars(fig, ax, x, ard_params, color, name, bottom=0):
color=color, edgecolor='k', linewidth=1.2,
label=name.replace("_"," "))
def plot_ARD(kernel, fignum=None, ax=None, title='', legend=False, filtering=None):
"""
If an ARD kernel is present, plot a bar representation using matplotlib
:param fignum: figure number of the plot
:param ax: matplotlib axis to plot on
:param title:
title of the plot,
pass '' to not print a title
pass None for a generic title
:param filtering: list of names, which to use for plotting ARD parameters.
Only kernels which match names in the list of names in filtering
will be used for plotting.
:type filtering: list of names to use for ARD plot
"""
fig, ax = ax_default(fignum,ax)
if title is None:
ax.set_title('ARD parameters, %s kernel' % kernel.name)
else:
ax.set_title(title)
Tango.reset()
bars = []
ard_params = np.atleast_2d(kernel.input_sensitivity(summarize=False))
bottom = 0
last_bottom = bottom
x = np.arange(kernel.input_dim)
if filtering is None:
filtering = kernel.parameter_names(recursive=False)
for i in range(ard_params.shape[0]):
if kernel.parameters[i].name in filtering:
c = Tango.nextMedium()
bars.append(plot_bars(fig, ax, x, ard_params[i,:], c, kernel.parameters[i].name, bottom=bottom))
last_bottom = ard_params[i,:]
bottom += last_bottom
else:
print("filtering out {}".format(kernel.parameters[i].name))
ax.set_xlim(-.5, kernel.input_dim - .5)
add_bar_labels(fig, ax, [bars[-1]], bottom=bottom-last_bottom)
if legend:
if title is '':
mode = 'expand'
if len(bars) > 1:
mode = 'expand'
ax.legend(bbox_to_anchor=(0., 1.02, 1., 1.02), loc=3,
ncol=len(bars), mode=mode, borderaxespad=0.)
fig.tight_layout(rect=(0, 0, 1, .9))
else:
ax.legend()
return ax
@ -111,7 +51,7 @@ def plot(kernel,x=None, fignum=None, ax=None, title=None, plot_limits=None, reso
:resolution: the resolution of the lines used in plotting
:mpl_kwargs avalid keyword arguments to pass through to matplotlib (e.g. lw=7)
"""
fig, ax = ax_default(fignum,ax)
_, ax = ax_default(fignum,ax)
if title is None:
ax.set_title('%s kernel' % kernel.name)

View file

@ -3,7 +3,7 @@
import numpy as np
try:
from . import Tango
from GPy.plotting.gpy_plot import Tango
from matplotlib import pyplot as pb
except:
pass

View file

@ -2,7 +2,6 @@
# Licensed under the BSD 3-clause license (see LICENSE.txt)
import numpy as np
from . import Tango
from .base_plots import gpplot, x_frame1D, x_frame2D,gperrors
from ...models.gp_coregionalized_regression import GPCoregionalizedRegression
from ...models.sparse_gp_coregionalized_regression import SparseGPCoregionalizedRegression
@ -11,7 +10,7 @@ from ...core.parameterization.variational import VariationalPosterior
from matplotlib import pyplot as plt
from .base_plots import gradient_fill
from functools import wraps
from .gpy_plot import Tango
def plot_data(self, which_data_rows='all',
which_data_ycols='all', visible_dims=None,

View file

@ -38,22 +38,36 @@ class MatplotlibPlots(AbstractPlottingLibrary):
super(MatplotlibPlots, self).__init__()
self._defaults = defaults.__dict__
def get_new_canvas(self, kwargs):
def get_new_canvas(self, plot_3d=False, kwargs):
if plot_3d:
from matplotlib.mplot3d import Axis3D # @UnusedImport
pr = '3d'
else: pr=None
if 'ax' in kwargs:
ax = kwargs.pop('ax')
elif 'num' in kwargs and 'figsize' in kwargs:
ax = plt.figure(num=kwargs.pop('num'), figsize=kwargs.pop('figsize')).add_subplot(111)
ax = plt.figure(num=kwargs.pop('num'), figsize=kwargs.pop('figsize')).add_subplot(111, projection=pr)
elif 'num' in kwargs:
ax = plt.figure(num=kwargs.pop('num')).add_subplot(111)
ax = plt.figure(num=kwargs.pop('num')).add_subplot(111, projection=pr)
elif 'figsize' in kwargs:
ax = plt.figure(figsize=kwargs.pop('figsize')).add_subplot(111)
ax = plt.figure(figsize=kwargs.pop('figsize')).add_subplot(111, projection=pr)
else:
ax = plt.figure().add_subplot(111)
ax = plt.figure().add_subplot(111, projection=pr)
# Add ax to kwargs to add all subsequent plots to this axis:
#kwargs['ax'] = ax
return ax, kwargs
def show_canvas(self, ax, plots):
def show_canvas(self, ax, plots, xlabel=None, ylabel=None,
zlabel=None, title=None, xlim=None, ylim=None,
zlim=None, legend=True, **kwargs):
ax.set_xlabel(xlabel)
ax.set_ylabel(ylabel)
if zlabel is not None:
ax.set_zlabel(zlabel)
ax.set_title(title)
try:
ax.autoscale_view()
ax.figure.canvas.draw()
@ -62,13 +76,13 @@ class MatplotlibPlots(AbstractPlottingLibrary):
pass
return plots
def scatter(self, ax, X, Y, **kwargs):
return ax.scatter(X, Y, **kwargs)
def scatter(self, ax, X, Y, color=None, label=None, **kwargs):
return ax.scatter(X, Y, c=color, label=label, **kwargs)
def plot(self, ax, X, Y, **kwargs):
return ax.plot(X, Y, **kwargs)
def plot(self, ax, X, Y, color=None, label=None, **kwargs):
return ax.plot(X, Y, color=color, label=label, **kwargs)
def plot_axis_lines(self, ax, X, **kwargs):
def plot_axis_lines(self, ax, X, color=None, label=None, **kwargs):
from matplotlib import transforms
from matplotlib.path import Path
if 'transform' not in kwargs:
@ -76,31 +90,44 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'marker' not in kwargs:
kwargs['marker'] = Path([[-.2,0.], [-.2,.5], [0.,1.], [.2,.5], [.2,0.], [-.2,0.]],
[Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY])
return ax.scatter(X, np.zeros_like(X), **kwargs)
return ax.scatter(X, np.zeros_like(X), c=color, label=label, **kwargs)
def xerrorbar(self, ax, X, Y, error, **kwargs):
def barplot(self, ax, x, height, width=0.8, bottom=0, color=None, label=None, **kwargs):
if 'align' not in kwargs:
kwargs['align'] = 'center'
return ax.bar(left=x, height=height, width=width,
bottom=bottom, label=label, color=color,
**kwargs)
def xerrorbar(self, ax, X, Y, error, color=None, label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none'
return ax.errorbar(X, Y, xerr=error, **kwargs)
return ax.errorbar(X, Y, xerr=error, ecolor=color, label=label, **kwargs)
def yerrorbar(self, ax, X, Y, error, **kwargs):
def yerrorbar(self, ax, X, Y, error, color=None, label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none'
return ax.errorbar(X, Y, yerr=error, **kwargs)
return ax.errorbar(X, Y, yerr=error, ecolor=color, label=label, **kwargs)
def imshow(self, ax, X, **kwargs):
return ax.imshow(**kwargs)
def imshow(self, ax, X, label=None, **kwargs):
return ax.imshow(X, label=label, **kwargs)
def contour(self, ax, X, Y, C, levels=20, **kwargs):
return ax.contour(X, Y, C, levels=np.linspace(C.min(), C.max(), levels), **kwargs)
def contour(self, ax, X, Y, C, levels=20, label=None, **kwargs):
return ax.contour(X, Y, C, levels=np.linspace(C.min(), C.max(), levels), label=label, **kwargs)
def fill_between(self, ax, X, lower, upper, **kwargs):
return ax.fill_between(X, lower, upper, **kwargs)
def fill_between(self, ax, X, lower, upper, color=None, label=None, **kwargs):
return ax.fill_between(X, lower, upper, facecolor=color, label=label, **kwargs)
def fill_gradient(self, canvas, X, percentiles, **kwargs):
def fill_gradient(self, canvas, X, percentiles, color=None, label=None, **kwargs):
ax = canvas
plots = []
if 'edgecolors' not in kwargs:
kwargs['edgecolors'] = 'none'
if 'facecolors' not in kwargs:
kwargs['facecolors'] = color
if 'facecolors' in kwargs:
kwargs['facecolor'] = kwargs.pop('facecolors')