Python matplotlib.ticker 模块,FormatStrFormatter() 实例源码
我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用matplotlib.ticker.FormatStrFormatter()。
def LDR(Time_Series):
columns=['Consume diesel', 'Lost Load', 'Energy PV','Curtailment','Energy Diesel',
'discharge energy from the Battery', 'Charge energy to the Battery',
'Energy_Demand', 'State_Of_Charge_Battery' ]
Sort_Values = Time_Series.sort('Energy_Demand', ascending=False)
index_values = []
for i in range(len(Time_Series)):
index_values.append((i+1)/float(len(Time_Series))*100)
Sort_Values = pd.DataFrame(Sort_Values.values/1000, columns=columns, index=index_values)
plt.figure()
ax = Sort_Values['Energy_Demand'].plot(style='k-',linewidth=1)
fmt = '%.0f%%' # Format you want the ticks,e.g. '40%'
xticks = mtick.FormatStrFormatter(fmt)
ax.xaxis.set_major_formatter(xticks)
ax.set_ylabel('Load (kWh)')
ax.set_xlabel('Percentage (%)')
plt.savefig('Results/LDR.png', bBox_inches='tight')
plt.show()
def draw2dsurface(X, Y, zf):
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(X, Y)
Z = X*0
for i in range(len(X)):
for j in range(len(X[0])):
Z[i][j] = zf([X[i][j], Y[i][j]])
surf = ax.plot_surface(X, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(np.min(Z.flatten()), np.max(Z.flatten()))
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, shrink=0.5, aspect=5)
# plt.show()
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 histplot(histogram, bins, ax=None, plot_kws=None, fig_kws=None, **kwargs):
"""Plot the histogram in the form of a bar chart."""
if isinstance(histogram, pd.DataFrame):
histogram = histogram.mean().values
if fig_kws is None:
fig_kws = dict(figsize=(16,8))
if plot_kws is None:
plot_kws = dict(alpha=1, edgecolor=None, linewidth=0)
if ax is None:
plt.figure(**fig_kws)
ax = plt.gca()
ax.bar(left=bins[:, 0], height=histogram, width=bins[:, -1] - bins[:,
align='edge', **plot_kws)
ax.semilogx()
ax.set_xlabel("$D_p \; [\mu m]$")
ax.xaxis.set_major_formatter(mtick.FormatStrFormatter("%.4g"))
return ax
def chartFormatAxisY(self, ax, k_dict, p_dict):
""""""
ax.tick_params(axis='y', **k_dict['k_major_y'])
ax.tick_params(axis='y', **k_dict['k_minor_y'])
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter(u"%.{0}f".format(int(p_dict['yAxisPrecision']))))
# Mirror Y axis values on Y2. Not all charts will support this option.
try:
if p_dict['yMirrorValues']:
ax.tick_params(labelright=True)
# A user may want tick labels only on Y2.
if not p_dict['yMirrorValuesAlsoY1']:
ax.tick_params(labelleft=False)
except Exception:
pass
return ax
def paint_surf(a, b, c, points=None):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
X = np.arange(-1, 1, 0.05)
Y = np.arange(-1, 0.05)
X, Y)
Z = -(X*a + Y*b + c)
surf = ax.plot_surface(X, linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, aspect=5)
if points != None:
x1 = points[:, 0]
y1 = points[:, 1]
z1 = points[:, 2]
ax.scatter(x1, y1, z1, c='r')
pl.show()
def paint_surfs(surfs, points, xlim=(-1.0, 1.0), ylim=(-1.0, zlim=(-1.1, 1.1)):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
for ans, surf_id in zip(surfs, range(len(surfs))):
a, c = ans[0][0], ans[0][1], ans[0][2]
X = np.arange(xlim[0], xlim[1], (xlim[1]-xlim[0])/100.0)
Y = np.arange(ylim[0], ylim[1], (ylim[1]-ylim[0])/100.0)
X, Y)
Z = -(X*a + Y*b + c)
# ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.coolwarm,linewidth=0,antialiased=False)
# fig.colorbar(s,shrink=0.5,aspect=5)
s = ax.plot_wireframe(X, rstride=15, cstride=15)
x1 = ans[2][:, 0]
y1 = ans[2][:, 1]
z1 = ans[2][:, c='crkgmy'[surf_id])
ax.set_zlim(zlim[0], zlim[1])
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# x1 = points[:,0]
# y1 = points[:,1]
# z1 = points[:,2]
# ax.scatter(x1,y1,z1,c='r')
pl.show()
def paint_surfs(surfs, 1.1), show = True):
fig = pl.figure()
ax = fig.add_subplot(111, Y)
Z = -(X*a + Y*b + c)
s = ax.plot_wireframe(X, 2]
# tan_color = np.ones((len(x1),len(y1))) * np.arctan2(len(surfs)) # c='crkgmycrkgmycrkgmycrkgmy'[surf_id]
# ax.scatter(x1,c='rcykgm'[surf_id % 6],marker='o^sd*+xp'[int(surf_id/6)])
ax.set_zlim(zlim[0], zlim[1])
# ax.set_ylim(ylim[0],ylim[1])
# ax.set_xlim(xlim[0],xlim[1])
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
if show:
pl.show()
def plot_single_cross_section_3d(data, select, subplot):
data = data[:, select]
# subplot.scatter(data[:,0],data[:,1],s=20,lw=0,edgecolors='none',alpha=1.0,
# subplot.plot(data[:,2],color='black',lw=1,alpha=0.4)
d = data
# subplot.plot(d[[-1,d[[-1,alpha=0.8,color='red')
# subplot.scatter(d[[-1,lw=10,alpha=0.3,marker=".",color='b')
d = data
subplot.scatter(d[:, d[:, 1], 2], s=4, alpha=1.0, lw=0.5,
c=vis._build_radial_colors(len(d)),
marker=".",
cmap=plt.cm.hsv)
subplot.plot(data[:, data[:, color='black', lw=0.2, alpha=0.9)
subplot.set_xlim([-0.01, 1.01])
subplot.set_ylim([-0.01, 1.01])
subplot.set_zlim([-0.01, 1.01])
ticks = []
subplot.xaxis.set_ticks(ticks)
subplot.yaxis.set_ticks(ticks)
subplot.zaxis.set_ticks(ticks)
subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
def plot_single_cross_section_line(data,color='b')
d = data
subplot.plot(data[:, lw=1, alpha=0.4)
subplot.set_xlim([-0.01, 1.01])
ticks = []
subplot.xaxis.set_ticks(ticks)
subplot.yaxis.set_ticks(ticks)
subplot.zaxis.set_ticks(ticks)
subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
def _plot_single_cross_section(data,
subplot.plot(data[:, alpha=0.4)
subplot.plot(data[[-1, data[[-1, alpha=0.8, color='red')
subplot.scatter(data[:,
c=_build_radial_colors(len(data)),
cmap=plt.cm.Spectral)
# data = np.vstack((data,np.asarray([data[0,:]])))
# subplot.plot(data[:,alpha=0.4)
subplot.set_xlabel('feature %d' % select[0], labelpad=-12)
subplot.set_ylabel('feature %d' % select[1], labelpad=-12)
subplot.set_xlim([-0.05, 1.05])
subplot.set_ylim([-0.05, 1.05])
subplot.xaxis.set_ticks([0, 1])
subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
subplot.yaxis.set_ticks([0, 1])
subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
def plot_portfolio_val(self,ax):
ax=ax
index = self.portfolio["Portfolio Value: "].index
data = self.portfolio["Portfolio Value: "].values
ind = np.arange(len(index)) #
formatter = MyFormatter(index) #
ax.xaxis.set_major_formatter(formatter) #
ax.plot(ind, data,color="orange") #
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
min_temp = np.min(data)
max_temp=np.max(data)
plt.xticks()
date_min = np.min(ind)
date_max = np.max(ind)
plt.xlim([date_min, date_max])
######designed for equally display codes!!!!!!
ax.fill_between(ind,0, color="navajowhite")
# fig.autofmt_xdate()
# cursor1 = Cursor_haunter(ax,ind,data,"Portfolio Value",1)
def plotResponseFEM(Ax,fi,f,H,Comp):
FS = 20
xTicks = (np.logspace(np.log(np.min(f)),np.log(np.max(f)),9))
Ylim = np.array([np.min(np.real(H)),np.max(np.real(H))])
Ax.grid('both', linestyle='-', linewidth=0.8, color=[0.8, 0.8, 0.8])
Ax.semilogx(f,0*f,color='k',linewidth=2)
Ax.semilogx(f,np.real(H),linewidth=4,label="Real")
Ax.semilogx(f,np.imag(H),ls='--',label="Imaginary")
Ax.semilogx(np.array([fi,fi]),1.1*Ylim,linewidth=3,color='r')
Ax.set_xbound(np.min(f),np.max(f))
Ax.set_ybound(1.1*Ylim)
Ax.set_xlabel('Frequency [Hz]',fontsize=FS+2)
Ax.tick_params(labelsize=FS-2)
Ax.yaxis.set_major_formatter(FormatStrFormatter('%.1e'))
if Comp == 'x':
Ax.set_ylabel('$\mathbf{Hx}$ [A/m]',fontsize=FS+4,labelpad=-5)
Ax.set_title('$\mathbf{Hx}$ Response at $\mathbf{Rx}$',fontsize=FS+6)
elif Comp == 'y':
Ax.set_ylabel('$\mathbf{Hy}$ [A/m]',labelpad=-5)
Ax.set_title('$\mathbf{Hy}$ Response at $\mathbf{Rx}$',fontsize=FS+6)
elif Comp == 'z':
Ax.set_ylabel('$\mathbf{Hz}$ [A/m]',labelpad=-5)
Ax.set_title('$\mathbf{Hz}$ Response at $\mathbf{Rx}$',fontsize=FS+6)
elif Comp == 'abs':
Ax.set_ylabel('$\mathbf{|H|}$ [A/m]',labelpad=-5)
Ax.set_title('$\mathbf{|H|}$ Response at $\mathbf{Rx}$',fontsize=FS+6)
if np.max(np.real(H[-1])) > 0.:
handles, labels = Ax.get_legend_handles_labels()
Ax.legend(handles, labels, loc='upper left', fontsize=FS)
elif np.max(np.real(H[-1])) < 0.:
handles, loc='lower left', fontsize=FS)
return Ax
def plot_InducedCurrent_FD(self,Ax,Is,fi):
FS = 20
R = self.R
L = self.L
Imax = np.max(-np.real(Is))
f = np.logspace(0,8,101)
Ax.grid('both', 0.8])
Ax.semilogx(f,-np.real(Is),label="$I_{Re}$")
Ax.semilogx(f,-np.imag(Is),label="$I_{Im}$")
Ax.semilogx(fi*np.array([1.,1.]),np.array([0,1.1*Imax]),color='r',ls='-',linewidth=3)
handles, fontsize=FS)
Ax.set_xlabel('Frequency [Hz]',fontsize=FS+2)
Ax.set_ylabel('$\mathbf{- \,I_s (\omega)}$ [A]',fontsize=FS+2,labelpad=-10)
Ax.set_title('Frequency Response',fontsize=FS)
Ax.set_ybound(0,1.1*Imax)
Ax.tick_params(labelsize=FS-2)
Ax.yaxis.set_major_formatter(FormatStrFormatter('%.1e'))
#R_str = '{:.3e}'.format(R)
#L_str = '{:.3e}'.format(L)
#f_str = '{:.3e}'.format(fi)
#EMF_str = '{:.2e}j'.format(EMFi.imag)
#I_str = '{:.2e} - {:.2e}j'.format(float(np.real(Isi)),np.abs(float(np.imag(Isi))))
#Ax.text(1.4,1.01*Imax,'$R$ = '+R_str+' $\Omega$',fontsize=FS)
#Ax.text(1.4,0.94*Imax,'$L$ = '+L_str+' H',0.87*Imax,'$f$ = '+f_str+' Hz',fontsize=FS,color='r')
#Ax.text(1.4,0.8*Imax,'$V$ = '+EMF_str+' V',0.73*Imax,'$I_s$ = '+I_str+' A',color='r')
return Ax
def plot_InducedCurrent_TD(self,ti,Vi,Isi):
FS = 20
R = self.R
L = self.L
Imax = np.max(Is)
t = np.logspace(-6,101)
Ax.grid('both', 0.8])
Ax.semilogx(t,linewidth=4)
Ax.semilogx(ti*np.array([1.,1.3*Imax]),linewidth=3)
Ax.set_xlabel('Time [s]',fontsize=FS+2)
Ax.set_ylabel('$\mathbf{I_s (\omega)}$ [A]',labelpad=-10)
Ax.set_title('Transient Induced Current',1.2*Imax)
Ax.tick_params(labelsize=FS-2)
Ax.yaxis.set_major_formatter(FormatStrFormatter('%.1e'))
#R_str = '{:.3e}'.format(R)
#L_str = '{:.3e}'.format(L)
#t_str = '{:.3e}'.format(ti)
#V_str = '{:.3e}'.format(Vi)
#I_str = '{:.3e}'.format(Isi)
#Ax.text(1.4e-6,1.12*Imax,fontsize=FS)
#Ax.text(1.4e-6,1.04*Imax,fontsize=FS)
#Ax.text(4e-2,'$t$ = '+t_str+' s',color='r')
#Ax.text(4e-2,'$V$ = '+V_str+' V',0.96*Imax,color='r')
return Ax
def plot_3d(model, phi, x_min, x_max, y_min, y_max, z_min, z_max, filename=None):
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(x_min, 5)
Y = np.arange(y_min, 5)
X, Y)
x, y = np.reshape(X, len(X)**2), np.reshape(Y, len(Y)**2)
Z = model(np.matrix(phi(np.array([x, y], dtype=np.float32).T)))
Z = np.reshape(Z, [len(X), len(X)])
# Plot the surface.
surf = ax.plot_surface(X, antialiased=False, shade=True)
# Customize the z axis.
ax.set_zlim(z_min, z_max)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, aspect=5)
plt.show()
def drawgraph(markethistory):
global graphdrawn
# Set up a graph and data sets
timeplots = []
priceplots = []
# Set up the graph
figgraph = figure(figsize=(10, 10), dpi=60)
# 2D Graph : 1 column,1 Row,1 Plot
axes = figgraph.add_subplot(111)
for key in markethistory:
figgraph.suptitle(markethistory[key].Label)
price = markethistory[key].Price
timestamp = markethistory[key].Timestamp
dtplot = datetime.datetime.fromtimestamp(timestamp)
timeplots.insert(len(timeplots), dtplot)
priceplots.insert(len(priceplots), price)
# Enforce 8 decimal places
axes.yaxis.set_major_formatter(FormatStrFormatter('%.8f'))
# Plot the graph
axes.plot(timeplots, priceplots)
# Canvas placed in main frame,controlled by figgraph
window.canvas = figureCanvasTkAgg(figgraph, master=window.mainframe)
window.canvas.get_tk_widget().place(relx=0.26, rely=0.01, relheight=0.46, relwidth=0.74)
window.canvas.draw()
graphdrawn = True
# Sell order list select event.
def DrawGridLine(products, m):
pj = products.map.projection
if m is plt:
# ???
plt.axis(pj.axis)
# ????????????
if pj.axis == 'on':
x_majorFormatter = FormatStrFormatter(pj.axisfmt[0])
y_majorFormatter = FormatStrFormatter(pj.axisfmt[1])
plt.gca().xaxis.set_major_formatter(x_majorFormatter)
plt.gca().yaxis.set_major_formatter(y_majorFormatter)
xaxis = plt.gca().xaxis
for label in xaxis.get_ticklabels():
label.set_fontproperties('DejaVu Sans')
label.set_fontsize(10)
yaxis = plt.gca().yaxis
for label in yaxis.get_ticklabels():
label.set_fontproperties('DejaVu Sans')
label.set_fontsize(10)
xaxis.set_visible(pj.lonlabels[3] == 1)
yaxis.set_visible(pj.latlabels[0] == 1)
return
else:
# draw parallels and meridians.
if pj.axis == 'on':
m.drawparallels(np.arange(-80., 81., 10.),
labels=pj.latlabels,
family='DejaVu Sans',
fontsize=10)
m.drawmeridians(np.arange(-180., 181.,
labels=pj.lonlabels,
fontsize=10)
def plot_surface(self):
fig = plt.figure(figsize = (8,8))
ax = fig.gca(projection='3d')
X, Y = np.meshgrid(np.arange(-1.00, 1.01, 2./(len(self.lattice_in) - 1)), np.arange(-1.00, 2./(len(self.lattice_in) - 1)))
surf = ax.plot_surface(X, self.lattice_in,cmap = cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, aspect=10)
def plot_price(smoothed_prices):
plot_over_map(10**(smoothed_prices - 3), norm=Lognorm(1.5e2, 1e3))
cb = plt.colorbar(fraction=0.03, ticks=sp.linspace(2e2, 1e3, 9), format=FormatStrFormatter(u'£%dk'))
cb.set_label(u'price paid (£1000s)')
plt.title('2015 Average Price Paid')
plt.gcf().set_size_inches(36, 36)
plt.gcf().savefig(os.path.join(OUTPUT_PATH, 'price_paid.png'), bBox_inches='tight')
def plot_relative_price(relative_prices):
plot_over_map(10**relative_prices, norm=Lognorm(0.5, 2))
cb = plt.colorbar(fraction=0.03, ticks=sp.linspace(0.5, 2, 4), format=FormatStrFormatter('x%.2f'))
cb.set_label('fraction of average price paid for commute time')
plt.title('Price relative to commute')
plt.gcf().set_size_inches(36, 'relative_price.png'), bBox_inches='tight')
def paint_points(points, show = True, title = '', xlim = None, ylim = None, zlim = None):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
if xlim == None:
xlim = (np.min(points[:, 0]), np.max(points[:, 0]))
if ylim == None:
ylim = (np.min(points[:, 1]), 1]))
if zlim == None:
zlim = (np.min(points[:, 2]), 2]))
x1 = points[:, 0]
y1 = points[:, 1]
z1 = points[:, 2]
ax.scatter(x1, c='r')
ax.set_zlim(zlim[0], zlim[1])
ax.set_ylim(ylim[0], ylim[1])
ax.set_xlim(xlim[0], xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_surfs(surfs, title = ''):
fig = pl.figure()
ax = fig.add_subplot(111, projection='3d')
xlim = (np.min(points[:, 0]))
ylim = (np.min(points[:, 1]))
zlim = (np.min(points[:, 2]))
for ans, c = ans.args[0], ans.args[1], ans.args[2]
X = np.arange(xlim[0], cstride=15)
x1 = ans.points[:, 0]
y1 = ans.points[:, 1]
z1 = ans.points[:, c='rcykgm'[surf_id % 6], marker='o^sd*+xp'[int(surf_id/6)])
ax.set_zlim(zlim[0],xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_surfs(surfs, xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def paint_points(points, xlim[1])
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
pl.title(title)
if show:
pl.show()
return fig
def plot_3d(self,ax,x1,x2,y1,y2): # give 3d plot the potential
self.x=linspace(x1,self.n)
self.y=linspace(y2,self.n)
self.x,self.y=meshgrid(self.x,self.y)
self.surf=ax.plot_surface(self.x,self.y,self.V, cmap=cm.coolwarm)
ax.set_xlim(x1,x2)
ax.set_ylim(y1,y2)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.01f'))
ax.set_xlabel('x (m)',fontsize=14)
ax.set_ylabel('y (m)',fontsize=14)
ax.set_zlabel('Electric potential (V)',fontsize=14)
ax.set_title('Potential near capacitor',fontsize=18)
def plot_3d(self,fontsize=18)
def plot_3d(self,y2): # give 3d plot the potential
self.x=linspace(x1,fontsize=18)
def _plot_single_cross_section_3d(data,
cmap=plt.cm.Spectral)
data = data[0::10]
# subplot.plot(data[:,lw=2,alpha=0.8)
# data = np.vstack((data, labelpad=-12)
subplot.set_zlabel('feature %d' % select[2], labelpad=-12)
subplot.set_xlim([-0.01, 1.01])
subplot.xaxis.set_ticks([0, 1])
subplot.yaxis.set_ticks([0, 1])
subplot.zaxis.set_ticks([0, 1])
subplot.xaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
subplot.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.0f'))
def plot_3d(objective_function, length=20):
"""
Plot 3D functions
:param objective_function:
:type objective_function:
:param length:
:type length:
:return:
:rtype:
"""
bounds = objective_function.get_bounds()
if len(bounds) != 2:
return
x_grid = np.linspace(bounds[0][0], bounds[0][1], length)
y_grid = np.linspace(bounds[1][0], bounds[1][1], length)
x_grid, y_grid = np.meshgrid(x_grid, y_grid)
grid = np.vstack((x_grid.flatten(), y_grid.flatten())).T
z_points = objective_function.evaluate(grid)
z_points = z_points.reshape(length, length)
fig = pyplot.figure()
axis = fig.gca(projection='3d')
surf = axis.plot_surface(x_grid, y_grid,
z_points,
cmap=cm.cool,
alpha=0.3)
axis.contour(x_grid.tolist(), y_grid.tolist(), z_points.tolist(),
zdir='z', offset=z_points.min(), cmap=cm.cool)
axis.set_xlim(bounds[0][0], bounds[0][1])
axis.set_ylim(bounds[1][0], bounds[1][1])
pyplot.title(objective_function.__class__.__name__)
axis.zaxis.set_major_locator(LinearLocator(10))
axis.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, aspect=5)
pyplot.show()
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, 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 plot_fisher_data(self, fisher_data, axes=None, fig=None,
linestyles=[], labels=[]):
"""
Args:
fisher_dat(tuple): Data from the fisher_decomposition function
*see docscring for deFinition*
Keyword Args:
axes(plt.Axes): *Ignored*
fig(plt.figure): A valid figure to plot on
linestyles(list): A list of valid linestyles *Ignored*
labels(list): A list of labels *Ignored*
"""
if fig is None:
fig = plt.figure()
else:
pass
# end
ax1 = plt.subplot(211)
ax2 = plt.subplot(212)
eigs = fisher_data[0]
eig_vects = fisher_data[1]
eig_func = fisher_data[2]
indep = fisher_data[3]
# ax1.bar(np.arange(eigs.shape[0]),eigs,width=0.9,
# edgecolor='none',orientation='vertical')
ax1.semilogy(eigs, 'sk')
ax1.set_xlabel("Eigenvalue number")
ax1.set_ylabel(r"Eigenvalue / Pa$^{-2}$")
ax1.set_xlim(-0.5, len(eigs) - 0.5)
ax1.set_ylim([0.1 * min(eigs[np.nonzero(eigs)]), 10 * max(eigs)])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
styles = ['-g', '-.b', '--m', ':k', '-c', '-.y', '--r'] *\
int(math.ceil(eig_func.shape[0] / 7.0))
for i in range(eig_func.shape[0]):
ax2.plot(indep, eig_func[i], styles[i],
label="{:d}".format(i))
# end
ax2.legend(loc='best')
ax2.get_legend().set_title("Eigen-\nfunctions", prop={'size': 7})
ax2.set_xlabel(r"Specific volume / cm$^3$ g$^{-1}$")
ax2.set_ylabel("Eigenfunction response / Pa")
fig.tight_layout()
return fig
def plot_convergence(self, hist, linestyles=['-k'], labels=[]):
"""
Args:
hist(tuple): Convergence history,elements
0. (list): MAP history
1. (list): DOF history
Keyword Args:
axes(plt.Axes): The axes on which to plot the figure,if None,
creates a new figure object on which to plot.
linestyles(list): Strings for the linestyles
labels(list): Strings for the labels
"""
if axes is None:
fig = plt.figure()
ax1 = fig.gca()
else:
fig = None
ax1 = axes
# end
ax1.semilogy(-np.array(hist[0]), linestyles[0])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
ax1.set_xlabel('Iteration number')
ax1.set_ylabel('Negative a posteriori log likelihood')
# fig = plt.figure()
# ax1 = fig.add_subplot(121)
# ax2 = fig.add_subplot(122)
# for i in range(dof_hist.shape[1]):
# ax1.plot(dof_hist[:,i]/dof_hist[0,i])
# # end
# fig.suptitle('Convergence of iterative process')
# ax1.set_ylabel('Spline knot value')
# ax1.set_xlabel('Iteration number')
# fig.savefig('EOS_convergence.pdf')
def plot_fisher_matrix(sens_matrix, exp, model, fig, lines=None):
"""
"""
fisher = exp.get_fisher_matrix(sens_matrix)
fisher_data = Bayesian.fisher_decomposition(fisher, tol=1E-3)
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
eigs = fisher_data[0]
eig_vects = fisher_data[1]
eig_func = fisher_data[2]
indep = fisher_data[3]
ax1.semilogy(eigs, 'sk')
ax1.set_xlabel("Eigenvalue number")
ax1.set_ylabel(r"Eigenvalue / Pa$^{-2}$")
ax1.set_xlim(-0.5, len(eigs) - 0.5)
ax1.set_ylim([0.1 * min(eigs[np.nonzero(eigs)]), 10 * max(eigs)])
ax1.xaxis.set_major_locator(MultipleLocator(1))
ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
styles = ['-g', '--r'] *\
int(math.ceil(eig_func.shape[0] / 7.0))
for i in range(eig_func.shape[0]):
ax2.plot(indep,
label="{:d}".format(i))
# end
# find rho=25.77 gpa
for line, name in lines:
ax2.axvline(line)
# end
ax2.legend(loc='best')
ax2.get_legend().set_title("Eigen-\nfunctions", prop={'size': 7})
ax2.set_xlabel(r"Density / g cm$^{-3}$ ")
ax2.set_ylabel("Eigenfunction response / Pa")
fig.tight_layout()
return fig
def plot_chart(self, values, center, lcl, ucl, title, newvalues=None):
ax.yaxis.tick_right()
ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.3f'))
num = len(values)
if isinstance(values[0], list):
num = len(values[0])
if newvalues:
ax.plot([num - 0.5] * 2, [lcl, ucl], 'k--')
ax.plot(values + newvalues, 'bo--')
num += len(newvalues)
newx = list(range(num))
newx[0] = -0.3
newx[-1] = num - 0.6
if isinstance(lcl, list) and isinstance(ucl, list):
ax.yaxis.set_ticks([center])
ax.plot([-0.3, num], [center, center], 'k-')
ax.plot(values, 'bo--')
ax.fill_between(newx, facecolor='green', alpha=0.4, step='mid')
ax.step(newx, 'r:', where='mid')
ax.step(newx, where='mid')
else:
ax.fill_between([-0.3, lcl], [ucl, alpha=0.4)
ax.yaxis.set_ticks([lcl, ucl])
ax.plot([0, 'k-')
ax.plot([0, 'r:')
ax.plot([0, 'r:')
if isinstance(values[0], list):
ax.plot(values[0], 'bo--')
ax.plot(values[1], 'bo--')
else:
ax.plot(values, 'bo--')
# Set the title
ax.set_title(title)
# Change de y limits of the graph
ylim = ax.get_ylim()
factor = 0.2
new_ylim = (ylim[0] + ylim[1]) / 2 + np.array((-0.5, 0.5)) * (ylim[1] - ylim[0]) * (1 + factor)
if lcl == 0:
ax.set_ylim([0, new_ylim[1]])
else:
ax.set_ylim(new_ylim)
# Change x ticks
new_xlim = [0, num]
ax.set_xlim([0, num] + np.array((-0.3, -0.6)))
ax.xaxis.set_ticks(np.arange(*new_xlim, 2))
def animation3D(agents, function, lb, ub, sr=False):
side = np.linspace(lb, 45)
X, Y = np.meshgrid(side, side)
zs = np.array([function([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_surface(X, cmap='jet', antialiased=False)
ax.set_xlim(lb, ub)
ax.set_ylim(lb, ub)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf, aspect=5)
iter = len(agents)
n = len(agents[0])
t = np.array([np.ones(n) * i for i in range(iter)]).flatten()
b = []
[[b.append(agent) for agent in epoch] for epoch in agents]
c = [function(x) for x in b]
a = np.asarray(b)
df = pd.DataFrame({"time": t, "x": a[:, "y": a[:, "z": c})
def update_graph(num):
data = df[df['time'] == num]
graph._offsets3d = (data.x, data.y, data.z)
title.set_text(function.__name__ + " " * 45 + 'iteration: {}'.format(
num))
title = ax.set_title(function.__name__ + " " * 45 + 'iteration: 0')
data = df[df['time'] == 0]
graph = ax.scatter(data.x, data.z, color='black')
ani = matplotlib.animation.FuncAnimation(fig, update_graph, iter,
interval=50, blit=False)
if sr:
ani.save('result.mp4')
plt.show()
def plot(path, costs):
'''
path: List of the different orders in which the nodes are visited
points: coordinates for the different nodes
costs: Cost of each iteration
'''
# Change figure size
plt.figure(figsize=(15,6))
'''
Plot Cost Function
'''
plt.subplot(121)
curve, = plt.plot(np.array(costs), label='distance(m)')
plt.ylabel("distance")
plt.xlabel("Iteration")
plt.grid(True)
plt.legend()
cost = str("%.2f" % round(costs[-1], 2))
plt.title("Final distance: " + cost)
'''
Plot TSP Route
'''
plt.subplot(122)
# Transform back to longitude/latitude
points = (points / 111000).tolist()
# Unpack the primary path and transform it into a list of ordered coordinates
x = []; y = []
for i in path:
x.append(points[i][1])
y.append(points[i][0])
x.append(points[path[0]][1])
y.append(points[path[0]][0])
# Plot line
plt.plot(x, y, 'c-', label='Route')
# Plot dot
plt.plot(x, 'bo', label='Location')
# Avoid scientific notation
ax = plt.gca()
ax.xaxis.set_major_formatter(FormatStrFormatter('%.3f'))
ax.yaxis.set_major_formatter(FormatStrFormatter('%.3f'))
# Set axis too slightly larger than the set of x and y
plt.xlim(min(x)*0.99999, max(x)*1.00001)
plt.ylim(min(y)*0.99999, max(y)*1.00001)
plt.xlabel("Longitude")
plt.ylabel("Latitude")
plt.title("TSP Route Visualization")
plt.grid(True)
plt.show()
def recursiveStaLtaCharacteristicParameters(trace):
'''
Plot a trace and the corresponding characteristic functions of the recursive STA/LTA trigger
for different STA and LTA window lengths.
:param trace: The recorded trace
:type trace: obspy.core.trace.Trace
:param staDur: STA duration in seconds
:param ltaDur: LTA duration in seconds
:param thrOn: Trigger on threshold
:parm thrOff: Trigger off threshold
'''
df = trace.stats.sampling_rate
npts = trace.stats.npts
t = np.arange(npts, dtype=np.float32) / df
cft = []
# STA LTA duration parameter variation
staLta = [
(1, 3),
(1, 20),
(0.01, 1),
(0.1,
(0.5, 5),
(2,
(4, 20)]
for i in range(9):
cft.append(obs.signal.trigger.recursive_sta_lta(trace.data, int(staLta[i][0]*df), int(staLta[i][1]*df)))
fig, axes = plt.subplots(10, figsize=(20, subplot_kw={'yticks': []})
# plot recorded trace
axes[0].plot(t, trace.data, 'k')
axes[0].yaxis.set_ticks(np.linspace(-2e-5, 2e-5, 3))
axes[0].set_ylim(-0.00003, 0.00003)
axes[0].yaxis.set_major_formatter(FormatStrFormatter('%.E'))
axes[0].set_ylabel('m/s')
# plot chracteristic functions
i = 0
for ax in axes[1:]:
#ax.add_subplot(10,1,i)
ax.plot(t, cft[i], 'k')
ax.text(0.075, 'sta='+ str(staLta[i][0]) + ',lta=' + str(staLta[i][1]), ha='center', va='center', transform=ax.transAxes)
ax.yaxis.set_ticks(np.linspace(0, int(np.floor(np.max(cft[i]))), 3))
ax.set_ylim(0, np.max(cft[i]+1))
i += 1
axes[9].set_xlabel("Time after %s [s]" % trace.stats.starttime.isoformat())
# no x ticks
for i in range(9):
axes[i].get_xaxis().set_ticks([])
fig.suptitle(trace.id)
plt.draw()
def __init__(self, time_array, truth, reading_array, estimate_array):
self.fig, (self.ax2, self.ax1) = plt.subplots(
1, sharey=True,
gridspec_kw={"width_ratios":[3, 1]},
figsize=(8, 4)
)
plt.tight_layout(pad=2.0)
self.time_array = time_array
self.estimate_array = estimate_array
self.ax1.set_ylim(0, 120)
self.ax1.set_xlim(0, 20)
self.ax1.set_xlabel("Probability")
self.ax1.xaxis.set_major_formatter(FormatStrFormatter('%d%%'))
self.estimate_line = self.ax1.plot(
[], [], color='purple', label='estimate')
self.lines = []
for sensor in reading_array:
self.lines += self.ax1.plot(
[], color=sensor.color, label=sensor.name)
self.truth_line = self.ax1.hlines(truth[0], 0, 20, color='red', label='Occupancy')
self.ax1.legend()
self.ax2.plot(time_array, label='Occupancy')
# self.ax2.set_ylim(0,150)
self.ax2.set_title("Train car occupancy over time")
self.ax2.set_xlabel("Time (minutes)")
self.ax2.set_ylabel("Occupants")
self.estimate_ts = self.ax2.plot(
[], label='estimate')
self.fill_lines = self.ax2.fill_between(
[], alpha=0.5)
self.truth = truth
self.reading_array = reading_array
super().__init__(
self.fig, self.update,
frames=len(time_array),
blit=True
)
def plot_price(self,ax):
ax=ax
for i in self.price_data:
index = self.price_data[i].index
data = self.price_data[i].values
ind = np.arange(len(index)) #
formatter = MyFormatter(index) #
ax.xaxis.set_major_formatter(formatter) #
ax.plot(ind, data) #
formatter = ticker.FormatStrFormatter('$%1.2f')
ax.yaxis.set_major_formatter(formatter)
min_temp = np.min(data)
max_temp=np.max(data)
plt.xticks()
######designed for equally display codes!!!!!!!
date_min = np.min(ind)
date_max = np.max(ind)
plt.xlim([date_min, date_max])
density_temp = len(ind) / 20
zip = np.arange(date_min, date_max, density_temp + 1)
plt.xticks(zip)
#start text
tickerr="AAPL"
current_price = Share(tickerr).get_price() # latest
open_price = Share(tickerr).get_open()
high_price=Share(tickerr).get_days_high()
low_price=Share(tickerr).get_days_low()
change_price = Share(tickerr).get_change()
current_time = Share(tickerr).get_Trade_datetime()
Last_price=Share(tickerr).get_prev_close()
volume=Share(tickerr).get_volume()
current_price="Current: "+current_price
open_price="Open: "+open_price
high_price="High: "+high_price
low_price="Low: "+low_price
Last_price="Last: "+Last_price
change_price="Chg: "+change_price
volume="Volume: "+volume
ss=current_time+' '+ current_price+" "+open_price+" "+high_price+" "+low_price+" "+Last_price+" "+volume+" "\
+change_price
plt.text(date_min+2,max_temp+12,ss,fontsize=15)
ax.fill_between(ind, min_temp - 10.0, color="lightsteelblue")
# fig.autofmt_xdate()
cursor1 = Cursor_haunter(ax, ind, "Close price", 1)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。