def saveAttention(input_sentence, attentions, outpath):
# Set up figure with colorbar
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
fig = plt.figure(figsize=(24,10), )
ax = fig.add_subplot(111)
cax = ax.matshow(attentions.cpu().numpy(), cmap='bone')
fig.colorbar(cax)
if input_sentence:
# Set up axes
ax.set_yticklabels([' '] + list(input_sentence) + [' '])
# Show label at every tick
ax.yaxis.set_major_locator(ticker.MultipleLocator(1))
plt.tight_layout()
plt.savefig(outpath)
plt.close('all')
python类ticker()的实例源码
plotting.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 35
收藏 0
点赞 0
评论 0
def _remove_labels_from_axis(axis):
for t in axis.get_majorticklabels():
t.set_visible(False)
try:
# set_visible will not be effective if
# minor axis has NullLocator and NullFormattor (default)
import matplotlib.ticker as ticker
if isinstance(axis.get_minor_locator(), ticker.NullLocator):
axis.set_minor_locator(ticker.AutoLocator())
if isinstance(axis.get_minor_formatter(), ticker.NullFormatter):
axis.set_minor_formatter(ticker.FormatStrFormatter(''))
for t in axis.get_minorticklabels():
t.set_visible(False)
except Exception: # pragma no cover
raise
axis.get_label().set_visible(False)
def visLoc(locs, label="NotSet"):
axis = lambda i: [loc[i] for loc in locs]
import matplotlib.ticker as ticker
fig, ax = plt.subplots()
#plt.grid(True)
ax.plot(axis(0), axis(1), 'g^', ms=2)
ylim = ax.get_ylim()
xlim = ax.get_xlim()
ax.set_xlim(min(xlim[0],ylim[0]) ,max(xlim[1],ylim[1]))
ax.set_ylim(min(xlim[0],ylim[0]) ,max(xlim[1],ylim[1]))
plt.title("Moving paths from " + label)
plt.xlabel("West -- East")
plt.ylabel("South -- North")
plt.show()
def savePlot(points, outpath):
plt.figure()
fig, ax = plt.subplots()
# this locator puts ticks at regular intervals
loc = ticker.MultipleLocator(base=0.2)
ax.yaxis.set_major_locator(loc)
plt.plot(points)
plt.savefig(outpath)
plt.close('all')
######################################################################
# This is a helper function to print time elapsed and estimated time
# remaining given the current time and progress %.
#
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, mappable, **kw):
# Ensure the given mappable's norm has appropriate vmin and vmax set
# even if mappable.draw has not yet been called.
mappable.autoscale_None()
self.mappable = mappable
kw['cmap'] = cmap = mappable.cmap
kw['norm'] = mappable.norm
if isinstance(mappable, contour.ContourSet):
CS = mappable
kw['alpha'] = mappable.get_alpha()
kw['boundaries'] = CS._levels
kw['values'] = CS.cvalues
kw['extend'] = CS.extend
#kw['ticks'] = CS._levels
kw.setdefault('ticks', ticker.FixedLocator(CS.levels, nbins=10))
kw['filled'] = CS.filled
else:
if getattr(cmap, 'colorbar_extend', False) is not False:
kw.setdefault('extend', cmap.colorbar_extend)
if isinstance(mappable, Artist):
kw['alpha'] = mappable.get_alpha()
ticks = kw.pop('ticks', None)
ticklabels = kw.pop('ticklabels', None)
self._base = ColorbarBase2(None, **kw)
if ticks:
self._base.set_ticks(ticks, update_ticks=False)
if ticks and ticklabels:
self._base.set_ticklabels(ticklabels, update_ticks=False)
def setLineSensor(self):
try:
self.compressLabel(self.sensorList)
x1=[]
x1pos=[]
labels1=[]
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.sensorList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
self.par1.xaxis.set_major_formatter(ticker.NullFormatter())
self.par1.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par1.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par1.xaxis.set_ticks(x1)
except Exception as _err:
print(_err)
logging.exception(_err)
pass
def setLineRBW(self):
self.compressLabel(self.rbwList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.rbwList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
# self.par2.spines["bottom"].set_position(("outward", 50))
# self.par2.xaxis.set_ticks_position('bottom')
# self.par2.set_xscale('log')
self.par2.xaxis.set_major_formatter(ticker.NullFormatter())
self.par2.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par2.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par2.xaxis.set_ticks(x1)
self.par2.xaxis.set_tick_params(which='minor',length=1,direction='out', pad=5, labelbottom='on')
self.par2.xaxis.set_tick_params(which='major',length=10,direction='out', pad=5,labelbottom='on')
except Exception as _err:
print(_err)
logging.exception(_err)
def InteractivePlaneProfile():
srcLoc = 0.
orientation = "X"
nRx = 100
def foo(Field, Sigma, Scale, Time):
fig = plt.figure(figsize=(8,4))
ax1 = plt.subplot(111)
r = np.linspace(-1000., 0., nRx)
val_ex, val_hy = PlaneEHfield(r, t=Time, sig=Sigma)
if Field == "Ex":
val = val_ex.flatten()
label = "Ex-field (V/m)"
elif Field == "Hy":
val = val_hy.flatten()
label = "Hy-field (A/m)"
if Scale == "log":
val_p, val_n = DisPosNegvalues(val)
ax1.plot(r, val_p, 'k-', lw=2)
ax1.plot(r, val_n, 'k--', lw=2)
ax1.set_yscale(Scale)
elif Scale == "linear":
ax1.plot(r, val, 'k-', lw=2)
ax1.set_yscale(Scale)
y = ax1.yaxis.get_majorticklocs()
yticksa = np.linspace(y.min(), y.max(), 3)
ax1.yaxis.set_ticks(yticksa)
ax1.yaxis.set_major_formatter(ticker.FormatStrFormatter("%.1e"))
ax1.set_xlim(0, -1000)
ax1.set_ylabel(label, color='k')
ax1.set_xlabel("Z (m)")
ax1.grid(True)
plt.show()
Q2 = widgets.interactive (foo
,Field=widgets.ToggleButtons(options=['Ex','Hy'], value='Ex')
,Sigma=widgets.FloatText(value=1, continuous_update=False, description='$\sigma$ (S/m)') \
,Scale=widgets.ToggleButtons(options=['log','linear'], value="linear") \
,Time=widgets.FloatSlider(min=0.01, max=1., step=0.01, value=0., description='$t$ (s)')
)
return Q2
def porestreamlines(polygon=None, rx=10., ry=10., Nx=100, Ny=100,
maxvalue=None, **fields):
"streamlines plot of vector field around nanopore"
# interpolate on regular mesh symmetric w.r.t. center axis
mesh2D = nanopores.RectangleMesh([-rx-0.1,-ry-0.1], [rx+0.1,ry+0.1], Nx, Ny)
fields2 = nanopores.convert2D(mesh2D, *(fields.values()))
# prepare polygon and copy to left half
settings = dict(closed=True, facecolor="#eeeeee", linewidth=3.,
edgecolor="black")
if polygon is not None:
polygon = np.array(polygon)
polygon_m = np.column_stack([-polygon[:,0], polygon[:,1]])
# prepare plots
Ny += 1
Nx += 1
Y, X = np.mgrid[-ry:ry:Ny*1j, -rx:rx:Nx*1j]
U = np.zeros((Ny,Nx))
V = np.zeros((Ny,Nx))
formt = matplotlib.ticker.FuncFormatter(fmt)
ticks = [0] + [10**n for n in range(-16, -9)]
# determine uniform color range from fields (maybe round to nearest 10-power)
if maxvalue is None:
maxvalue = max(dolfin.norm(F.vector(), "linf") for F in fields2)
#maxvalue = 10**int(np.log10(maxvalue))
for i, F in enumerate(fields2):
Fstr = fields.keys()[i]
fig, ax = plt.subplots(figsize=(5, 4.5), num=Fstr)
# fill array with function values
for y in range(Ny):
for x in range(Nx):
f = F(X[y][x], Y[y][x])
U[y][x] = f[0]
V[y][x] = f[1]
# streamplot with logarithmic scale
strength = np.sqrt(U*U+V*V)
norm = matplotlib.colors.SymLogNorm(linthresh=ticks[1], linscale=1.0,
vmin=0., vmax=maxvalue)
strm = plt.streamplot(X, Y, U, V, arrowsize=1.5, linewidth=1.5, density=1.5,
cmap=cm.viridis, color=strength, norm=norm)
plt.colorbar(strm.lines, ticks=ticks, format=formt)
plt.xlabel('x [nm]') #, fontsize=20)
plt.ylabel('z [nm]') #, fontsize=20)
# plot pore polygon on top
if polygon is not None:
patch = patches.Polygon(polygon, **settings)
patchm = patches.Polygon(polygon_m, **settings)
patch.set_zorder(10)
patchm.set_zorder(10)
ax.add_patch(patch)
ax.add_patch(patchm)
def __init__(self, data, cbname, cblinthresh, cmap, extent, zlim,
figure_size, fontsize, aspect, figure, axes, cax):
from matplotlib.ticker import ScalarFormatter
self._draw_colorbar = True
self._draw_axes = True
self._fontsize = fontsize
self._figure_size = figure_size
# Compute layout
fontscale = float(fontsize) / 18.0
if fontscale < 1.0:
fontscale = np.sqrt(fontscale)
if iterable(figure_size):
fsize = figure_size[0]
else:
fsize = figure_size
self._cb_size = 0.0375*fsize
self._ax_text_size = [1.2*fontscale, 0.9*fontscale]
self._top_buff_size = 0.30*fontscale
self._aspect = ((extent[1] - extent[0])/(extent[3] - extent[2])).in_cgs()
self._unit_aspect = aspect
size, axrect, caxrect = self._get_best_layout()
super(WindowPlotMPL, self).__init__(
size, axrect, caxrect, zlim, figure, axes, cax)
self._init_image(data, cbname, cblinthresh, cmap, extent, aspect)
# In matplotlib 2.1 and newer we'll be able to do this using
# self.image.axes.ticklabel_format
# See https://github.com/matplotlib/matplotlib/pull/6337
formatter = ScalarFormatter(useMathText=True)
formatter.set_scientific(True)
formatter.set_powerlimits((-2, 3))
self.image.axes.xaxis.set_major_formatter(formatter)
self.image.axes.yaxis.set_major_formatter(formatter)
if cbname == 'linear':
self.cb.formatter.set_scientific(True)
self.cb.formatter.set_powerlimits((-2, 3))
self.cb.update_ticks()
def plot(self, filename):
r"""Save an image file of the transfer function.
This function loads up matplotlib, plots all of the constituent
transfer functions and saves.
Parameters
----------
filename : string
The file to save out the plot as.
Examples
--------
>>> tf = ColorTransferFunction( (-10.0, -5.0) )
>>> tf.add_layers(8)
>>> tf.plot("sample.png")
"""
from matplotlib import pyplot
from matplotlib.ticker import FuncFormatter
pyplot.clf()
ax = pyplot.axes()
i_data = np.zeros((self.alpha.x.size, self.funcs[0].y.size, 3))
i_data[:,:,0] = np.outer(np.ones(self.alpha.x.size), self.funcs[0].y)
i_data[:,:,1] = np.outer(np.ones(self.alpha.x.size), self.funcs[1].y)
i_data[:,:,2] = np.outer(np.ones(self.alpha.x.size), self.funcs[2].y)
ax.imshow(i_data, origin='lower')
ax.fill_between(np.arange(self.alpha.y.size), self.alpha.x.size * self.alpha.y, y2=self.alpha.x.size, color='white')
ax.set_xlim(0, self.alpha.x.size)
xticks = np.arange(np.ceil(self.alpha.x[0]), np.floor(self.alpha.x[-1]) + 1, 1) - self.alpha.x[0]
xticks *= (self.alpha.x.size-1) / (self.alpha.x[-1] - self.alpha.x[0])
ax.xaxis.set_ticks(xticks)
def x_format(x, pos):
return "%.1f" % (x * (self.alpha.x[-1] - self.alpha.x[0]) / (self.alpha.x.size-1) + self.alpha.x[0])
ax.xaxis.set_major_formatter(FuncFormatter(x_format))
yticks = np.linspace(0,1,5) * self.alpha.y.size
ax.yaxis.set_ticks(yticks)
def y_format(y, pos):
return (y / self.alpha.y.size)
ax.yaxis.set_major_formatter(FuncFormatter(y_format))
ax.set_ylabel("Transmission")
ax.set_xlabel("Value")
pyplot.savefig(filename)
def show(self, ax=None):
r"""Display an image of the transfer function
This function loads up matplotlib and displays the current transfer function.
Parameters
----------
Examples
--------
>>> tf = TransferFunction( (-10.0, -5.0) )
>>> tf.add_gaussian(-9.0, 0.01, 1.0)
>>> tf.show()
"""
from matplotlib import pyplot
from matplotlib.ticker import FuncFormatter
pyplot.clf()
ax = pyplot.axes()
i_data = np.zeros((self.alpha.x.size, self.funcs[0].y.size, 3))
i_data[:,:,0] = np.outer(np.ones(self.alpha.x.size), self.funcs[0].y)
i_data[:,:,1] = np.outer(np.ones(self.alpha.x.size), self.funcs[1].y)
i_data[:,:,2] = np.outer(np.ones(self.alpha.x.size), self.funcs[2].y)
ax.imshow(i_data, origin='lower')
ax.fill_between(np.arange(self.alpha.y.size), self.alpha.x.size * self.alpha.y, y2=self.alpha.x.size, color='white')
ax.set_xlim(0, self.alpha.x.size)
xticks = np.arange(np.ceil(self.alpha.x[0]), np.floor(self.alpha.x[-1]) + 1, 1) - self.alpha.x[0]
xticks *= (self.alpha.x.size-1) / (self.alpha.x[-1] - self.alpha.x[0])
if len(xticks) > 5:
xticks = xticks[::len(xticks)/5]
ax.xaxis.set_ticks(xticks)
def x_format(x, pos):
return "%.1f" % (x * (self.alpha.x[-1] - self.alpha.x[0]) / (self.alpha.x.size-1) + self.alpha.x[0])
ax.xaxis.set_major_formatter(FuncFormatter(x_format))
yticks = np.linspace(0,1,5) * self.alpha.y.size
ax.yaxis.set_ticks(yticks)
def y_format(y, pos):
s = '%0.2f' % ( y )
return s
ax.yaxis.set_major_formatter(FuncFormatter(y_format))
ax.set_ylabel("Opacity")
ax.set_xlabel("Value")
def multi_bull_eyes(multi_data, cbar=None, cmaps=None, normalisations=None,
global_title=None, canvas_title='title', titles=None, units=None, raidal_subdivisions=(2, 8, 8, 11),
centered=(True, False, False, True), add_nomenclatures=(True, True, True, True),
pfi_where_to_save=None, show=True):
plt.clf()
n_fig = len(multi_data)
if cbar is None:
cbar = [True] * n_fig
if cmaps is None:
cmaps = [mpl.cm.viridis] * n_fig
if normalisations is None:
normalisations = [mpl.colors.Normalize(vmin=np.min(multi_data[i]), vmax=np.max(multi_data[i]))
for i in range(n_fig)]
if titles is None:
titles = ['Title {}'.format(i) for i in range(n_fig)]
h_space = 0.15 / n_fig
h_dim_fig = .8
w_dim_fig = .8 / n_fig
def fmt(x, pos):
# a, b = '{:.2e}'.format(x).split('e')
# b = int(b)
# return r'${} \times 10^{{{}}}$'.format(a, b)
return r"${:.4g}$".format(x)
# Make a figure and axes with dimensions as desired.
fig = plt.figure(figsize=(3 * n_fig, 4))
fig.canvas.set_window_title(canvas_title)
if global_title is not None:
plt.suptitle(global_title)
for n in range(n_fig):
origin_fig = (h_space * (n + 1) + w_dim_fig * n, 0.15)
ax = fig.add_axes([origin_fig[0], origin_fig[1], w_dim_fig, h_dim_fig], polar=True)
bulls_eye(ax, multi_data[n], cmap=cmaps[n], norm=normalisations[n], raidal_subdivisions=raidal_subdivisions,
centered=centered, add_nomenclatures=add_nomenclatures[n])
ax.set_title(titles[n], size=10)
if cbar[n]:
origin_cbar = (h_space * (n + 1) + w_dim_fig * n, .15)
axl = fig.add_axes([origin_cbar[0], origin_cbar[1], w_dim_fig, .05])
cb1 = mpl.colorbar.ColorbarBase(axl, cmap=cmaps[n], norm=normalisations[n], orientation='horizontal',
format=ticker.FuncFormatter(fmt))
cb1.ax.tick_params(labelsize=8)
if units is not None:
cb1.set_label(units[n])
if pfi_where_to_save is not None:
plt.savefig(pfi_where_to_save, format='pdf', dpi=330)
if show:
plt.show()
def setLineAMP(self):
self.compressLabel(self.ampList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.ampList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
if not self.line2TextFlag:
# self.par3.text(-0.05,-0.33,"amp",horizontalalignment='left',transform=self.host.transAxes)
# self.par3.text(-0.05,-0.40,"att",horizontalalignment='left',transform=self.host.transAxes)
# self.par3.spines["bottom"].set_position(("outward", 90))
self.par3.xaxis.set_ticks_position('bottom')
self.par3.xaxis.set_major_formatter(ticker.NullFormatter())
self.par3.xaxis.set_minor_formatter(ticker.NullFormatter())
self.par3.xaxis.set_tick_params(which='minor',length=1,direction='in', pad=-10, labelbottom='on')
self.par3.xaxis.set_tick_params(which='major',length=10,direction='in', pad=-20,labelbottom='on')
self.line2TextFlag = True
self.par3.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par3.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par3.xaxis.set_ticks(x1)
#set color for autorange indication
_Ret = self.par3.xaxis.get_minorticklabels()
n = 0
for i in _Ret:
if self.ampList[n].color =='r':
i._color = 'r' #sorry, found no other access
if n < len(self.ampList) - 1:
n += 1
except Exception as _err:
print(_err)
logging.exception(_err)
pass
def setLineATT(self):
self.compressLabel(self.attList)
try:
x1 = []
x1pos = []
labels1 = []
j = -1
x1pos.append(0)
labels1.append('')
# self.setTestData()
for i in self.attList:
if i.startX > j:
x1.append(i.startX)
j = i.startX
x1.append(i.stopX)
x1pos.append(i.labelPos)
labels1.append(i.label)
# self.par4.spines["bottom"].set_position(("outward", 90))
# self.par4.xaxis.set_ticks_position('bottom')
# # self.par1.set_xlim(1e3,1e9)
# self.par4.set_xscale('log')
self.par4.xaxis.set_major_formatter(ticker.NullFormatter())
self.par4.xaxis.set_minor_locator(ticker.FixedLocator(x1pos))
self.par4.xaxis.set_minor_formatter(ticker.FixedFormatter(labels1))
self.par4.xaxis.set_ticks(x1)
self.par4.xaxis.set_tick_params(which='minor',length=1,direction='out', pad=5, labelbottom='on')
self.par4.xaxis.set_tick_params(which='major',length=10,direction='out', pad=5,labelbottom='on')
_Ret = self.par4.xaxis.get_minorticklabels()
n = 0
for i in _Ret:
if self.attList[n].color =='r':
i._color = 'red'
if n < len(self.attList) - 1:
n += 1
# self.signalGraphUpdate.emit()
except Exception as _err:
print(_err)
logging.exception(_err)
pass
def onNewPlot(self, data):
# print ('Graph: new Plot')
assert isinstance(data,DB_Handler_TPL3.Tpl3Plot)
self.host.set_xlim(data.x1,data.x2)
self.host.set_ylim(data.y1,data.y2)
self.par1.set_xlim(data.x1,data.x2)
self.par2.set_xlim(data.x1,data.x2)
self.par3.set_xlim(data.x1,data.x2)
self.par4.set_xlim(data.x1,data.x2)
self.par1.set_xscale('log')
self.par1.xaxis.set_major_formatter(ticker.NullFormatter())
self.par1.xaxis.set_minor_formatter(ticker.NullFormatter())
self.par2.set_xscale('log')
self.par2.xaxis.set_major_formatter(ticker.NullFormatter())
self.par2.xaxis.set_minor_formatter(ticker.NullFormatter())
self.par3.set_xscale('log')
self.par3.xaxis.set_major_formatter(ticker.NullFormatter())
self.par3.xaxis.set_minor_formatter(ticker.NullFormatter())
self.par4.set_xscale('log')
self.par4.xaxis.set_major_formatter(ticker.NullFormatter())
self.par4.xaxis.set_minor_formatter(ticker.NullFormatter())
#self.setWindowTitle(data.plot_title)
self.signalShowTitle.emit(data.plot_title)
#self.figure_canvas.draw()
descriptionData = []
descriptionData.append(data.eut)
descriptionData.append(data.test_no)
descriptionData.append(data.serial_no)
descriptionData.append(data.model_no)
descriptionData.append(data.model_name)
descriptionData.append(data.date_time)
descriptionData.append(data.company)
descriptionData.append(data.technician)
descriptionData.append(data.plan_title)
descriptionData.append(data.routines)
descriptionData.append(data.plot_no)
descriptionData.append(data.annotations)
sList = data.sources.split(',')
if len(sList) > 0:
for s in sList:
descriptionData.append(s)
self.setText(descriptionData)
self.signalGraphUpdate.emit()
self.currentStaticPlotFlag = False
pass