def make_split(ratio, gap=0.12):
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
from matplotlib.ticker import MaxNLocator
cax = plt.gca()
box = cax.get_position()
xmin, ymin = box.xmin, box.ymin
xmax, ymax = box.xmax, box.ymax
gs = GridSpec(2, 1, height_ratios=[ratio, 1 - ratio], left=xmin, right=xmax, bottom=ymin, top=ymax)
gs.update(hspace=gap)
ax = plt.subplot(gs[0])
plt.setp(ax.get_xticklabels(), visible=False)
bx = plt.subplot(gs[1], sharex=ax)
return ax, bx
python类MaxNLocator()的实例源码
def inertia(self, explained_inertia):
fig, ax = plt.subplots()
ax.grid('on')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
ax.plot(explained_inertia, color=SEABORN['blue'], label='Normalized inertia')
ax.plot(explained_inertia, 'o', color=SEABORN['cyan'])
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.margins(0.05)
ax.set_ylim(ymax=1)
ax.set_title('Component contributions to inertia')
ax.set_xlabel('Component number')
ax.set_ylabel('Normalized inertia')
ax.legend(loc='best')
return fig, ax
def _plot_walk(self, ax, parameter, data, truth=None, extents=None,
convolve=None, color=None): # pragma: no cover
if extents is not None:
ax.set_ylim(extents)
assert convolve is None or isinstance(convolve, int), \
"Convolve must be an integer pixel window width"
x = np.arange(data.size)
ax.set_xlim(0, x[-1])
ax.set_ylabel(parameter)
if color is None:
color = "#0345A1"
ax.scatter(x, data, c=color, s=2, marker=".", edgecolors="none", alpha=0.5)
max_ticks = self.parent.config["max_ticks"]
ax.yaxis.set_major_locator(MaxNLocator(max_ticks, prune="lower"))
if convolve is not None:
color2 = self.parent.color_finder.scale_colour(color, 0.5)
filt = np.ones(convolve) / convolve
filtered = np.convolve(data, filt, mode="same")
ax.plot(x[:-1], filtered[:-1], ls=':', color=color2, alpha=1)
if truth is not None:
ax.axhline(truth, **self.parent.config_truth)
def plotKurtosisVsLvls(ax, runs, *args, **kwargs):
"""Plots El, Vl vs TOL of @runs, as
returned by MIMCDatabase.readRunData()
ax is in instance of matplotlib.axes
"""
args, kwargs = __normalize_fmt(args, kwargs)
ax.set_xlabel(r'$\ell$')
ax.set_ylabel(r'$\textnormal{Kurt}_\ell$')
ax.set_yscale('log')
fnNorm = kwargs.pop("fnNorm")
if "__calc_moments" in kwargs:
central_delta_moments, _, _, _, _ = kwargs.pop("__calc_moments")
else:
central_delta_moments, _, _, _, _ = __calc_moments(runs,
seed=kwargs.pop('seed', None),
direction=kwargs.pop('direction',
None),
fnNorm=fnNorm)
Vl = central_delta_moments[:, 1]
E4l = central_delta_moments[:, 3]
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
line = ax.plot(np.arange(0, len(Vl)), E4l/Vl**2, *args, **kwargs)
return line[0].get_xydata(), [line]
def plotSkewnessVsLvls(ax, runs, *args, **kwargs):
"""Plots El, Vl vs TOL of @runs, as
returned by MIMCDatabase.readRunData()
ax is in instance of matplotlib.axes
"""
args, kwargs = __normalize_fmt(args, kwargs)
ax.set_xlabel(r'$\ell$')
ax.set_ylabel(r'$\textnormal{Skew}_\ell$')
ax.set_yscale('log')
fnNorm = kwargs.pop("fnNorm")
if "__calc_moments" in kwargs:
central_delta_moments, _, _, _, _ = kwargs.pop("__calc_moments")
else:
central_delta_moments, _, _, _, _ = __calc_moments(runs,
seed=kwargs.pop('seed', None),
direction=kwargs.pop('direction',
None),
fnNorm=fnNorm)
Vl = central_delta_moments[:, 1]
E3l = np.abs(central_delta_moments[:, 2])
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
line = ax.plot(np.arange(0, len(Vl)), E3l/Vl**1.5, *args, **kwargs)
return line[0].get_xydata(), [line]
def showResult(date, scales, power, time_scale, window, file_name):
# y_ticks = np.arange(0, 15, 2)
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
fig, ax = plt.subplots()
ax.xaxis.set_major_locator(YearLocator(time_scale))
# ax.set_yticks(y_ticks)
ax.xaxis.set_major_locator(mticker.MaxNLocator(5))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))
ax.contourf(date, scales, power, 100)
# ax.set_yscale('log')
print("Wavelet saved to", file_name)
fig.savefig(file_name)
# fig.show()
# fig.waitforbuttonpress()
def paper_single_mult_ax(nrows=1, ncols=1, **kwargs):
#import matplotlib as mpl
paper_single(FF=max(nrows,ncols))
f, ax = plt.subplots(nrows=nrows, ncols=ncols, **kwargs)
plt.minorticks_on()
ylocator6 = plt.MaxNLocator(5)
xlocator6 = plt.MaxNLocator(6)
if len(ax.shape) > 1:
for axrow in ax:
for axcol in axrow:
axcol.xaxis.set_major_locator(xlocator6)
axcol.yaxis.set_major_locator(ylocator6)
else:
for axcol in ax:
axcol.xaxis.set_major_locator(xlocator6)
axcol.yaxis.set_major_locator(ylocator6)
return f, ax
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144):
if save_as_png:
save_as = 'png'
else:
save_as = 'pdf'
filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0]
model = get_model_type(sol)
if draw or save:
fig, ax = plt.subplots(figsize=(4,3))
deviance = sol.MDL.trace('deviance')[:]
sampler_state = sol.MDL.get_state()["sampler"]
x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"])
plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC))
plt.xlabel("Iteration")
plt.ylabel("Model deviance")
plt.legend(numpoints=1, loc="best", fontsize=9)
plt.grid('on')
if sampler_state["_burn"] == 0:
plt.xscale('log')
else:
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.tight_layout()
if save:
save_where = '/Figures/ModelDeviance/'
working_path = getcwd().replace("\\", "/")+"/"
save_path = working_path+save_where
print("\nSaving model deviance figure in:\n", save_path)
if not path.exists(save_path):
makedirs(save_path)
fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight')
try: plt.close(fig)
except: pass
if draw: return fig
else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144):
if save_as_png:
save_as = 'png'
else:
save_as = 'pdf'
filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0]
model = get_model_type(sol)
if draw or save:
fig, ax = plt.subplots(figsize=(4,3))
logp = logp_trace(sol.MDL)
sampler_state = sol.MDL.get_state()["sampler"]
x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"])
plt.plot(x, logp, "-", color="C3")
plt.xlabel("Iteration")
plt.ylabel("Log-likelihood")
plt.legend(numpoints=1, loc="best", fontsize=9)
plt.grid('on')
if sampler_state["_burn"] == 0:
plt.xscale('log')
else:
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.tight_layout()
if save:
save_where = '/Figures/LogLikelihood/'
working_path = getcwd().replace("\\", "/")+"/"
save_path = working_path+save_where
print("\nSaving logp trace figure in:\n", save_path)
if not path.exists(save_path):
makedirs(save_path)
fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight')
try: plt.close(fig)
except: pass
if draw: return fig
else: return None
def plot_deviance(sol, save=False, draw=True, save_as_png=True, fig_dpi=144):
if save_as_png:
save_as = 'png'
else:
save_as = 'pdf'
filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0]
model = get_model_type(sol)
if draw or save:
fig, ax = plt.subplots(figsize=(4,3))
deviance = sol.MDL.trace('deviance')[:]
sampler_state = sol.MDL.get_state()["sampler"]
x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"])
plt.plot(x, deviance, "-", color="C3", label="Model deviance\nDIC = %.2f\nBPIC = %.2f" %(sol.MDL.DIC,sol.MDL.BPIC))
plt.xlabel("Iteration")
plt.ylabel("Model deviance")
plt.legend(numpoints=1, loc="best")
plt.grid('on')
if sampler_state["_burn"] == 0:
plt.xscale('log')
else:
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.tight_layout()
if save:
save_where = '/Figures/ModelDeviance/'
working_path = getcwd().replace("\\", "/")+"/"
save_path = working_path+save_where
print("\nSaving model deviance figure in:\n", save_path)
if not path.exists(save_path):
makedirs(save_path)
fig.savefig(save_path+'ModelDeviance-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight')
try: plt.close(fig)
except: pass
if draw: return fig
else: return None
def plot_logp(sol, save=False, draw=True, save_as_png=True, fig_dpi=144):
if save_as_png:
save_as = 'png'
else:
save_as = 'pdf'
filename = sol.filename.replace("\\", "/").split("/")[-1].split(".")[0]
model = get_model_type(sol)
if draw or save:
fig, ax = plt.subplots(figsize=(4,3))
logp = logp_trace(sol.MDL)
sampler_state = sol.MDL.get_state()["sampler"]
x = np.arange(sampler_state["_burn"]+1, sampler_state["_iter"]+1, sampler_state["_thin"])
plt.plot(x, logp, "-", color="C3")
plt.xlabel("Iteration")
plt.ylabel("Log-likelihood")
plt.legend(numpoints=1, loc="best")
plt.grid('on')
if sampler_state["_burn"] == 0:
plt.xscale('log')
else:
plt.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
fig.tight_layout()
if save:
save_where = '/Figures/LogLikelihood/'
working_path = getcwd().replace("\\", "/")+"/"
save_path = working_path+save_where
print("\nSaving logp trace figure in:\n", save_path)
if not path.exists(save_path):
makedirs(save_path)
fig.savefig(save_path+'LogLikelihood-%s-%s.%s'%(model,filename,save_as), dpi=fig_dpi, bbox_inches='tight')
try: plt.close(fig)
except: pass
if draw: return fig
else: return None
def heatmap(data, save_file='heatmap.png'):
ax = plt.figure().gca()
ax.yaxis.set_major_locator(MaxNLocator(integer=True))
ax.yaxis.set_major_locator(MultipleLocator(5))
plt.pcolor(data, cmap=plt.cm.jet)
plt.savefig(save_file)
# plt.show()
def plot_pull(data, func):
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
ax, bx = make_split(0.8)
plt.sca(ax)
x, y, norm = histpoints(data)
lower, upper = ax.get_xlim()
xs = np.linspace(lower, upper, 200)
plt.plot(xs, norm * func(xs), 'b-')
#plt.gca().yaxis.set_major_locator(MaxNLocator(prune='lower'))
plt.sca(bx)
resid = y[1] - norm * func(x)
err = np.zeros_like(resid)
err[resid >= 0] = y[0][resid >= 0]
err[resid < 0] = y[2][resid < 0]
pull = resid / err
plt.errorbar(x, pull, yerr=1, color='k', fmt='o')
plt.ylim(-5, 5)
plt.axhline(0, color='b')
plt.sca(ax)
return ax, bx
def visualise(self, marks, counts):
N = len(marks)
ind = range(N)
_, ax = plt.subplots()
ax.bar(ind, counts, color='#4286f4')
ax.set_ylabel('Posts')
ax.set_xticks(ind)
ax.yaxis.set_major_locator(MaxNLocator(nbins=20, integer=True, min_n_ticks=1))
step = N // 12 + 1
labels = [self.format_time(mark) if i % step == 0 else '' for i, mark in enumerate(marks)]
ax.set_xticklabels(labels, rotation=45, fontsize=10)
return self.save()
def cumulative_inertia(self, cumulative_explained_inertia, threshold):
fig, ax = plt.subplots()
ax.grid('on')
ax.xaxis.set_ticks_position('none')
ax.yaxis.set_ticks_position('none')
# Plot threshold line
ax.axhline(y=threshold, color=SEABORN['red'], label='Threshold',
linestyle='--')
# Plot first value above threshold line
try:
index_above_threshold = [
i >= threshold
for i in cumulative_explained_inertia
].index(True)
ax.axvline(x=index_above_threshold, color=SEABORN['green'],
label='First component above threshold',
linestyle='--')
except ValueError:
pass
# Plot inertia percentages curve
ax.plot(cumulative_explained_inertia, color=SEABORN['blue'],
label='Normalized cumulative inertia')
ax.plot(cumulative_explained_inertia, 'o', color=SEABORN['blue'])
ax.xaxis.set_major_locator(ticker.MaxNLocator(integer=True))
ax.margins(0.05, 0.15)
ax.set_ylim(ymin=0)
ax.set_title('Cumulative component contributions to inertia')
ax.set_xlabel('Component number')
ax.set_ylabel('Normalized cumulative inertia')
ax.legend(loc='best')
return fig, ax
def plot_ohlcv(self, df):
fig, ax = plt.subplots()
# Plot the candlestick
candlestick2_ohlc(ax, df['open'], df['high'], df['low'], df['close'],
width=1, colorup='g', colordown='r', alpha=0.5)
# shift y-limits of the candlestick plot so that there is space
# at the bottom for the volume bar chart
pad = 0.25
yl = ax.get_ylim()
ax.set_ylim(yl[0] - (yl[1] - yl[0]) * pad, yl[1])
# Add a seconds axis for the volume overlay
ax2 = ax.twinx()
ax2.set_position(
matplotlib.transforms.Bbox([[0.125, 0.1], [0.9, 0.26]]))
# Plot the volume overlay
# bc = volume_overlay(ax2, df['open'], df['close'], df['volume'],
# colorup='g', alpha=0.5, width=1)
ax.xaxis.set_major_locator(ticker.MaxNLocator(6))
def mydate(x, pos):
try:
return df.index[int(x)]
except IndexError:
return ''
ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))
plt.margins(0)
plt.show()
def __init__(self, max_n_ticks, calendar, date_unit, min_n_ticks=3):
# The date unit must be in the form of days since ...
self.max_n_ticks = max_n_ticks
self.min_n_ticks = min_n_ticks
self._max_n_locator = mticker.MaxNLocator(max_n_ticks, integer=True)
self._max_n_locator_days = mticker.MaxNLocator(
max_n_ticks, integer=True, steps=[1, 2, 4, 7, 14])
self.calendar = calendar
self.date_unit = date_unit
if not self.date_unit.lower().startswith('days since'):
msg = 'The date unit must be days since for a NetCDF time locator.'
raise ValueError(msg)
self._cached_resolution = {}
def __init__(self, *args, **kwargs):
mticker.MaxNLocator.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs):
return mticker.MaxNLocator.__call__(self, *args, **kwargs)
# at most 5 ticks, pruning the upper and lower so they don't overlap
# with other ticks
#ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))
#ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))
def plot_index_and_sentiment(tick_seq, shindex_seq, sentiment_seq, date):
if len(tick_seq) != len(shindex_seq) or len(tick_seq) != len(sentiment_seq):
print('error(plot) : three sequence length is not same')
return
x = range(len(shindex_seq))
labels = tick_seq
y1 = shindex_seq
y2 = sentiment_seq
def format_fn(tick_val, tick_pos):
if int(tick_val) in x:
return labels[int(tick_val)]
else:
return ''
fig = plt.figure(figsize=(12,8))
p1 = fig.add_subplot(111)
p1.xaxis.set_major_formatter(FuncFormatter(format_fn))
p1.xaxis.set_major_locator(MaxNLocator(integer=True, nbins=12))
delta = shindex_seq[len(shindex_seq) - 1] - shindex_seq[0]
if delta > 0:
p1.plot(x, y1, label="$SCI$", color="red", linewidth=1)
else:
p1.plot(x, y1, label="$SCI$", color="green", linewidth=1)
p1.plot(x, y2, 'b--', label="$ISI$", color="blue", linewidth=1)
plt.title("Shanghai Composite Index(SCI) & Investor Sentiment Index(ISI)")
plt.xlabel("Time(5min)")
plt.ylabel("Index Value")
plt.legend()
# plt.show()
global subdir
filepath = './Pic/' + subdir + '/' + date + '.png'
plt.savefig(filepath)
def __init__(self, *args, **kwargs):
mticker.MaxNLocator.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs):
return mticker.MaxNLocator.__call__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
mticker.MaxNLocator.__init__(self, *args, **kwargs)
def __call__(self, *args, **kwargs):
return mticker.MaxNLocator.__call__(self, *args, **kwargs)
#plt.rc('axes', grid=True)
cifar10_custom_dataset_gap.py 文件源码
项目:pytorch_60min_blitz
作者: kyuhyoung
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def main():
dir_data = './data'
ext_img = 'png'
#n_epoch = 100
n_epoch = 50
#n_img_per_batch = 40
n_img_per_batch = 60
#n_img_per_batch = 1
n_worker = 4
interval_train_loss = int(round(20000 / n_img_per_batch)) * n_img_per_batch
is_gpu = torch.cuda.device_count() > 0
transform = transforms.Compose(
[transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])
di_set_transform = {'train' : transform, 'test' : transform}
#fig = plt.figure(num=None, figsize=(1, 2), dpi=500)
fig = plt.figure(num=None, figsize=(12, 18), dpi=100)
plt.ion()
ax_loss_train = fig.add_subplot(2, 1, 1)
ax_loss_train.set_title('Avg. train loss per image vs. # train input images')
ax_loss_train.xaxis.set_major_locator(MaxNLocator(integer=True))
ax_loss_val = fig.add_subplot(2, 1, 2)
ax_loss_val.set_title('Avg. val. loss per image vs. # train input images')
ax_loss_val.xaxis.set_major_locator(MaxNLocator(integer=True))
trainloader, testloader, net, criterion, optimizer, scheduler, li_class = \
initialize(
is_gpu, dir_data, di_set_transform, ext_img, n_img_per_batch, n_worker)
#print('[%s] lap of initializing : %d sec' % (lap_sec))
kolor = np.random.rand(3)
#if 2 == i_m:
# a = 0
train(is_gpu, trainloader, testloader, net, criterion, optimizer, scheduler, #li_class,
n_epoch, ax_loss_train, ax_loss_val,
kolor, interval_train_loss)
print('Finished all.')
plt.pause(1000)
return
def _set_cbticks(cbrange, cb_kws):
"""Set colorbar ticks.
Adjust colorbar range if using a discrete colorbar so that the ticks fall
in the middle of each level.
Parameters:
cbrange (list):
Colorbar range.
cb_kws (dict):
Keyword args to set and draw colorbar.
Return:
tuple: colorbar range, colorbar tick numbers
"""
if cb_kws.get('log_cb'):
ticks = _log_cbticks(cbrange)
else:
try:
ticks = MaxNLocator(cb_kws.get('n_ticks', 7)).tick_values(*cbrange)
except AttributeError:
print('AttributeError: MaxNLocator instance has no attribute ``tick_values``.')
# if discrete colorbar, offset upper and lower cbrange so ticks are in center of each level
if cb_kws.get('n_levels', None) is not None:
offset = (ticks[1] - ticks[0]) / 2.
cbrange = [ticks[0] - offset, ticks[-1] + offset]
if cb_kws.get('tick_everyother', False):
ticks = ticks[::2]
return cbrange, ticks
submission_evaluation.py 文件源码
项目:evaluation-toolkit
作者: lightfield-analysis
项目源码
文件源码
阅读 24
收藏 0
点赞 0
评论 0
def add_colorbar(cm, bins, fontsize=5):
cb = plt.colorbar(cm, shrink=0.9)
cb.outline.set_linewidth(0)
cb.locator = ticker.MaxNLocator(nbins=bins)
cb.ax.tick_params(labelsize=fontsize)
cb.update_ticks()
def create_colorbar(cm, cax, colorbar_bins=8, fontsize=None, linewidth=0):
cb = plt.colorbar(mappable=cm, cax=cax)
if fontsize is not None:
cb.ax.tick_params(labelsize=fontsize)
cb.outline.set_linewidth(linewidth)
cb.locator = ticker.MaxNLocator(nbins=colorbar_bins)
cb.update_ticks()
def graphData(stock):
stockFile=stock+".txt"
date,closep,highp,lowp,openp,volume= np.loadtxt(stockFile,delimiter=',',unpack=True,
converters={0: mdates.strpdate2num('%Y%m%d')})
fig=plt.figure()
ax1=plt.subplot(1,1,1) # how much by how much by
ax1.plot(date,openp)
ax1.plot(date,highp)
ax1.plot(date,lowp)
ax1.plot(date,closep)
#pretty it up
ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max10days
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
# rotate
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(45)
plt.show()
def _set_integer_tick_labels(axis, labels):
"""Use labels dict to set labels on axis"""
axis.set_major_formatter(FuncFormatter(lambda x, _: labels.get(x, '')))
axis.set_major_locator(MaxNLocator(integer=True))