Commit 3a927f49 authored by Phil Jones's avatar Phil Jones

Cleaning up plotting functions and switching to using `pykat.style` throughout.

parent 8aa7ae70
...@@ -479,17 +479,6 @@ class KatRun(object): ...@@ -479,17 +479,6 @@ class KatRun(object):
if yaxis is not None: if yaxis is not None:
kat.yaxis = yaxis kat.yaxis = yaxis
if "log" in kat.yaxis:
if kat.xaxis.scale == "log":
plot_cmd = pyplot.loglog
else:
plot_cmd = pyplot.semilogy
else:
if kat.xaxis.scale == "log":
plot_cmd = pyplot.semilogx
else:
plot_cmd = pyplot.plot
dual_plot = False dual_plot = False
_func1 = np.abs _func1 = np.abs
_func2 = None _func2 = None
...@@ -497,20 +486,43 @@ class KatRun(object): ...@@ -497,20 +486,43 @@ class KatRun(object):
plot_cmd1 = None plot_cmd1 = None
plot_cmd2 = None plot_cmd2 = None
if "re:im" in kat.yaxis or "abs:deg" in kat.yaxis or "db:deg" in kat.yaxis:
dual_plot = True
if dual_plot:
fig = plt.figure(width="full", height=1)
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
else:
fig = plt.figure(width="full")
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1
if "log" in kat.yaxis:
if kat.xaxis.scale == "log":
plot_cmd1 = ax1.loglog
plot_cmd2 = ax2.loglog
else:
plot_cmd1 = ax1.semilogy
plot_cmd2 = ax2.semilogy
else:
if kat.xaxis.scale == "log":
plot_cmd1 = ax1.semilogx
plot_cmd2 = ax2.semilogx
else:
plot_cmd1 = ax1.plot
plot_cmd2 = ax2.plot
if "re:im" in kat.yaxis: if "re:im" in kat.yaxis:
_func1 = np.real _func1 = np.real
_func2 = np.imag _func2 = np.imag
plot_cmd1 = plot_cmd2 = plot_cmd
dual_plot = True
elif "abs:deg" in kat.yaxis: elif "abs:deg" in kat.yaxis:
_func1 = np.abs _func1 = np.abs
_func2 = lambda x: np.rad2deg(np.angle(x)) _func2 = lambda x: np.rad2deg(np.angle(x))
plot_cmd1 = plot_cmd plot_cmd2 = ax2.plot if kat.xaxis.scale == "lin" else ax2.semilogx
plot_cmd2 = pyplot.plot if kat.xaxis.scale == "lin" else pyplot.semilogx
dual_plot = True
elif "db:deg" in kat.yaxis: elif "db:deg" in kat.yaxis:
if "db" not in original_yaxis: if "db" not in original_yaxis:
_func1 = lambda x: 10*np.log10(x) _func1 = lambda x: 10*np.log10(x)
...@@ -519,33 +531,24 @@ class KatRun(object): ...@@ -519,33 +531,24 @@ class KatRun(object):
_func2 = lambda x: np.rad2deg(np.angle(x)) _func2 = lambda x: np.rad2deg(np.angle(x))
plot_cmd1 = plot_cmd plot_cmd2 = ax2.plot if kat.xaxis.scale == "lin" else ax2.semilogx
plot_cmd2 = pyplot.plot if kat.xaxis.scale == "lin" else pyplot.semilogx
dual_plot = True
elif "abs" in kat.yaxis: elif "abs" in kat.yaxis:
# _func1 = np.abs # _func1 = np.abs
_func1 = np.real _func1 = np.real
plot_cmd1 = plot_cmd
elif "db" in kat.yaxis: elif "db" in kat.yaxis:
if "db" not in original_yaxis: if "db" not in original_yaxis:
_func1 = lambda x: 10*np.log10(x) _func1 = lambda x: 10*np.log10(x)
else: else:
_func1 = lambda x: x _func1 = lambda x: x
plot_cmd1 = plot_cmd
elif "deg" in kat.yaxis: elif "deg" in kat.yaxis:
_func1 = lambda x: np.rad2deg(np.angle(x)) _func1 = lambda x: np.rad2deg(np.angle(x))
plot_cmd1 = plot_cmd
if dual_plot:
fig = plt.figure(width="full", height=1)
else:
fig = plt.figure(width="full")
if detectors is None: if detectors is None:
detectors = [lbl.split()[0] for lbl in self.ylabels] detectors = [lbl.split()[0] for lbl in self.ylabels]
detectors = list(set(detectors)) detectors = list(set(detectors))
detectors.sort() detectors.sort()
...@@ -553,17 +556,12 @@ class KatRun(object): ...@@ -553,17 +556,12 @@ class KatRun(object):
for det in detectors: for det in detectors:
if not hasattr(kat, det) or (hasattr(kat, det) and not getattr(kat, det).noplot): if not hasattr(kat, det) or (hasattr(kat, det) and not getattr(kat, det).noplot):
if dual_plot:
ax = pyplot.subplot(2,1,1)
if styles is not None and det in styles: if styles is not None and det in styles:
l, = plot_cmd1(_x, _func1(self[det])/pykat.SI[y1scale], styles[det], label=det) l, = plot_cmd1(_x, _func1(self[det])/pykat.SI[y1scale], styles[det], label=det)
else: else:
l, = plot_cmd1(_x, _func1(self[det])/pykat.SI[y1scale], label=det) l, = plot_cmd1(_x, _func1(self[det])/pykat.SI[y1scale], label=det)
if dual_plot: if dual_plot:
pyplot.subplot(2,1,2)
plot_cmd2(_x, _func2(self[det])/pykat.SI[y2scale], color=l.get_color(), ls=l.get_linestyle(), label=det) plot_cmd2(_x, _func2(self[det])/pykat.SI[y2scale], color=l.get_color(), ls=l.get_linestyle(), label=det)
if dual_plot: if dual_plot:
...@@ -598,33 +596,33 @@ class KatRun(object): ...@@ -598,33 +596,33 @@ class KatRun(object):
font_label_size = pyplot.rcParams["font.size"]-1 font_label_size = pyplot.rcParams["font.size"]-1
if dual_plot: if dual_plot:
ax = pyplot.subplot(2,1,1) #ax = plt.subplot(2,1,1)
pyplot.xlabel(xlabel, fontsize=font_label_size) ax1.set_xlabel(xlabel, fontsize=font_label_size)
pyplot.ylabel(ylabel, fontsize=font_label_size) ax1.set_ylabel(ylabel, fontsize=font_label_size)
pyplot.xlim(xlim[0], xlim[1]) ax1.set_xlim(xlim[0], xlim[1])
if ylim is not None: if ylim is not None:
pyplot.ylim(ylim[0],ylim[1]) ax1.set_ylim(ylim[0],ylim[1])
if title is not None: if title is not None:
pyplot.title(title, fontsize=font_label_size) ax1.set_title(title, fontsize=font_label_size)
pyplot.subplot(2,1,2) #plt.subplot(2,1,2)
pyplot.xlabel(x2label, fontsize=font_label_size) ax2.set_xlabel(x2label, fontsize=font_label_size)
pyplot.ylabel(y2label, fontsize=font_label_size) ax2.set_ylabel(y2label, fontsize=font_label_size)
pyplot.xlim(x2lim[0], x2lim[1]) ax2.set_xlim(x2lim[0], x2lim[1])
if y2lim is not None: if y2lim is not None:
pyplot.ylim(y2lim[0],y2lim[1]) ax2.set_ylim(y2lim[0],y2lim[1])
else: else:
pyplot.xlabel(xlabel, fontsize=font_label_size) ax1.set_xlabel(xlabel, fontsize=font_label_size)
pyplot.ylabel(ylabel) ax1.set_ylabel(ylabel)
pyplot.xlim(xlim[0], xlim[1]) ax1.set_xlim(xlim[0], xlim[1])
if title is not None: if title is not None:
pyplot.title(title, fontsize=font_label_size) ax1.set_title(title, fontsize=font_label_size)
if ylim is not None: if ylim is not None:
pyplot.ylim(ylim[0],ylim[1]) ax1.set_ylim(ylim[0],ylim[1])
pyplot.margins(0, 0.05) pyplot.margins(0, 0.05)
pyplot.tight_layout() pyplot.tight_layout()
...@@ -3643,4 +3641,4 @@ class kat(object): ...@@ -3643,4 +3641,4 @@ class kat(object):
return bt return bt
# printing pykat logo on first input # printing pykat logo on first input
kat.logo() #kat.logo()
...@@ -9,105 +9,93 @@ from __future__ import division ...@@ -9,105 +9,93 @@ from __future__ import division
from __future__ import print_function from __future__ import print_function
from __future__ import unicode_literals from __future__ import unicode_literals
# Should be either display (showing in windows) or paper (saving for paper/report/etc.)
__mode__ = None
__DPI__ = None __DPI__ = None
def in_ipython(): def in_ipython():
try: try:
cfg = get_ipython() __IPYTHON__
return True
except NameError: except NameError:
return False return False
else:
return True
def init_pykat_plotting(mode="display", dpi=100, fmts=None):
# `mode` should be either display (showing in windows)
# or paper (saving for paper/report/etc.)
def init_pykat_plotting(mode="display", dpi=None, fmts=None):
import matplotlib as mpl import matplotlib as mpl
import pykat.style
__DPI__ = int(dpi)
if fmts is None: if fmts is None:
fmts=['svg', 'pdf'] fmts = ['svg']
if in_ipython(): if in_ipython():
try: try:
from IPython.display import set_matplotlib_formats from IPython.display import set_matplotlib_formats
set_matplotlib_formats(*fmts)
ipy = get_ipython() ipy = get_ipython()
ipy.magic("matplotlib inline") ipy.magic("matplotlib inline")
except: set_matplotlib_formats(*fmts)
except NameError:
pass pass
if mode == "display": if mode == "display":
__mode__ = mode pykat.style.use(["default"])
elif mode == "paper": elif mode == "paper":
__mode__ = mode
mpl.use("pgf") mpl.use("pgf")
pykat.style.use(["default", "paper"])
else:
raise (BaseException(
"Plotting mode must be either 'display' or 'paper'."))
pgf_with_pdflatex = { if dpi is None:
"pgf.texsystem": "pdflatex", __DPI__ = mpl.rcParams['figure.dpi']
"text.usetex": True,
"pgf.preamble": [
r"\\usepackage{amsmath, amssymb}",
r"\\usepackage{mathtools, siunitx}" ,
r"\\usepackage{amsmath}",
r"\\usepackage[utf8x]{inputenc}",
r"\\usepackage[T1]{fontenc}"
]
}
mpl.rcParams.update(pgf_with_pdflatex)
else: else:
raise(BaseException("Plotting mode must be either 'display' or 'paper'.")) __DPI__ = int(dpi)
mpl.rcParams.update({'figure.dpi': __DPI__})
mpl.rcParams.update({'savefig.dpi': __DPI__})
if (mpl.__version__ < '1.5'): if (mpl.__version__ < '1.5'):
mpl.rcParams['axes.color_cycle'] = ['b', 'r', 'k', 'g', 'c', 'm', 'y'] # prop_cycle doesn't exist pre-1.5, and unknown rcParams are ignored,
else: # so we have to hardcode the color cycle
mpl.rcParams['axes.prop_cycle']=mpl.cycler('color', ['b', 'r', 'k', 'g', 'c', 'm', 'y']) mpl.rcParams.update({'axes.color_cycle': ['0000FF', 'FF0000', '000000', '00FF00', 'FF00FF']})
mpl.rcParams['lines.linewidth'] = 1.2
mpl.rcParams.update({"figure.figsize": (6, 3.708)}) def figure(width=None, height=None, textwidth=None, **kwargs):
mpl.rcParams.update({'font.size': 11})
mpl.rcParams.update({'figure.dpi': __DPI__})
mpl.rcParams.update({'savefig.dpi': __DPI__})
mpl.rcParams.update({'font.family': "serif"})
mpl.rcParams.update({'axes.grid': True})
mpl.rcParams.update({'axes.titlesize': "medium"})
mpl.rcParams.update({'axes.xmargin': 0})
mpl.rcParams.update({'legend.fontsize': "small"})
mpl.rcParams.update({'axes.axisbelow': True})
mpl.rcParams.update({'grid.linewidth': 0.25})
mpl.rcParams.update({'grid.linestyle': ":"})
mpl.rcParams.update({'grid.color': (0.6,0.6,0.6,1)})
mpl.rcParams.update({'savefig.bbox': "tight"})
mpl.rcParams.update({'savefig.pad_inches': 0.05})
mpl.rcParams.update({'xtick.labelsize': "small"})
mpl.rcParams.update({'ytick.labelsize': "small"})
mpl.rcParams.update({'axes.formatter.useoffset': True})
def figure(width="full", height=0.618, textwidth=6, **kwargs):
""" """
Options: Options:
width: 'full', 'half' (0.49*textwidth) (default: full) width: 'full', 'half' (0.49*textwidth) (default: None (use current
height: relative height to width (default: 1/golden ratio = 0.618) value))
textwidth: Width of text in inches (default: 9.84252 in = 25 cm ) height: relative height to width (default: None (use current value))
textwidth: Width of text in inches (default: None (use current value))
""" """
import matplotlib as mpl
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
fig_size = mpl.rcParams["figure.figsize"]
if width is None:
width = "full"
if height is None:
height = fig_size[1] / fig_size[0]
if textwidth is None:
textwidth = fig_size[0]
if width == "full": if width == "full":
fig_size = [textwidth, textwidth*height] fig_size[0] = textwidth
elif width == "half": elif width == "half":
fig_size = [textwidth*0.49, textwidth*height*0.49] fig_size[0] = 0.49 * textwidth
fig_size[1] = 0.49 * textwidth * height
else: else:
raise(BaseException("width must be either 'full' or 'half'.")) raise (BaseException("width must be either 'full', 'half' or None."))
fig = plt.figure(figsize=fig_size, dpi=__DPI__) fig = plt.figure(figsize=fig_size, dpi=__DPI__)
return fig return fig
def subplot(*args, **kwargs):
import matplotlib.pyplot as plt
ax = plt.subplot(*args, **kwargs)
return ax
...@@ -8,6 +8,7 @@ style_dir = os.path.split(os.path.realpath(__file__))[0] ...@@ -8,6 +8,7 @@ style_dir = os.path.split(os.path.realpath(__file__))[0]
available = [os.path.splitext(f)[0] available = [os.path.splitext(f)[0]
for f in os.listdir(style_dir) if f.endswith(".mplstyle")] for f in os.listdir(style_dir) if f.endswith(".mplstyle")]
def get_style_path(style): def get_style_path(style):
if isinstance(style, str) or hasattr(style, 'keys'): if isinstance(style, str) or hasattr(style, 'keys'):
# If name is a single str or dict, make it a single element list. # If name is a single str or dict, make it a single element list.
...@@ -18,10 +19,12 @@ def get_style_path(style): ...@@ -18,10 +19,12 @@ def get_style_path(style):
styles)) styles))
return styles return styles
def use(style): def use(style):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
plt.style.use(get_style_path(style)) plt.style.use(get_style_path(style))
def context(style, after_reset=False): def context(style, after_reset=False):
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
return plt.style.context(get_style_path(style), after_reset) return plt.style.context(get_style_path(style), after_reset)
...@@ -3,15 +3,18 @@ patch.facecolor: r ...@@ -3,15 +3,18 @@ patch.facecolor: r
# FONT # FONT
font.size : 11 font.size : 11
font.family : serif
# TEXT # TEXT
text.usetex : False text.usetex : False
# AXES # AXES
axes.grid : True axes.grid : True
axes.formatter.useoffset : True axes.formatter.useoffset : False
axes.formatter.use_locale : False axes.formatter.use_locale : False
axes.prop_cycle: cycler('color', ['0000FF', 'FF0000', '000000', '00FF00', 'FF00FF']) axes.prop_cycle : cycler('color', ['0000FF', 'FF0000', '000000', '00FF00', 'FF00FF'])
axes.axisbelow : True
axes.xmargin : 0
#TICKS #TICKS
xtick.labelsize : 9 xtick.labelsize : 9
...@@ -27,6 +30,9 @@ figure.titlesize : 12 ...@@ -27,6 +30,9 @@ figure.titlesize : 12
figure.figsize : 6, 3.708 figure.figsize : 6, 3.708
figure.dpi : 96 figure.dpi : 96
# LINES
lines.linewidth : 1.2
# IMAGES # IMAGES
image.cmap : magma image.cmap : magma
image.origin : lower image.origin : lower
...@@ -34,6 +40,7 @@ image.origin : lower ...@@ -34,6 +40,7 @@ image.origin : lower
# SAVING FIGURES # SAVING FIGURES
savefig.dpi : 300 savefig.dpi : 300
savefig.bbox : tight savefig.bbox : tight
savefig.pad_inches : 0.05
pdf.compression : 9 pdf.compression : 9
pdf.fonttype : 42 pdf.fonttype : 42
# FONT # FONT
font.family : serif
font.size : 9 font.size : 9
# FIGURE # FIGURE
...@@ -7,3 +6,7 @@ figure.figsize : 6.69291, 4.13645 ...@@ -7,3 +6,7 @@ figure.figsize : 6.69291, 4.13645
# TEXT # TEXT
text.usetex : True text.usetex : True
# PGF
pgf.texsystem : pdflatex
pgf.preamble: \usepackage{amsmath}, \usepackage{amssymb}, \usepackage{mathtools}, \usepackage{siunitx}, \usepackage{amsmath}, \usepackage[utf8x]{inputenc}, \usepackage[T1]{fontenc}
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