本文整理汇总了Python中mpld3.show函数的典型用法代码示例。如果您正苦于以下问题:Python show函数的具体用法?Python show怎么用?Python show使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了show函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: showNetwork
def showNetwork(struct, weights, labels):
nbLayers = len(struct)
networkXY = []
colors = ['b', 'r']
for layer in range(nbLayers):
layerXY = []
if layer != 4:
sumWeightsNeuron = np.sum(np.abs(weights['layer_' + str(layer)]['param_0']), axis=1)
maxSumWeights = np.max(sumWeightsNeuron)
for neuron in range(struct[layer]):
neuronXY = (layer*10, neuron-(struct[layer]-1)/2.)
if layer != 4 :
inputScatters = plt.scatter(neuronXY[0],neuronXY[1], alpha=(sumWeightsNeuron[neuron]/maxSumWeights)**2)
else :
inputScatters = plt.scatter(neuronXY[0],neuronXY[1], alpha=1)
layerXY.append(neuronXY)
networkXY.append(layerXY)
tooltip = mpld3.plugins.PointLabelTooltip(inputScatters, labels=labels)
if layer != 0:
print(weights['layer_' + str(layer-1)]['param_0'].value)
maxWeights = np.amax(np.abs(weights['layer_' + str(layer-1)]['param_0']))
for neuronLayer in range(struct[layer]):
for neuronLayerP in range(struct[layer-1]):
print(layer, neuronLayer, neuronLayerP, maxWeights)
plt.plot([networkXY[layer][neuronLayer][0],networkXY[layer-1][neuronLayerP][0]],
[networkXY[layer][neuronLayer][1],networkXY[layer-1][neuronLayerP][1]],
#alpha=1-np.exp(-((weights['layer_' + str(layer-1)]['param_0'][neuronLayerP][neuronLayer])/3)**2)
alpha = (weights['layer_' + str(layer-1)]['param_0'][neuronLayerP][neuronLayer] / maxWeights)**2,
c = colors[int(weights['layer_' + str(layer-1)]['param_0'][neuronLayerP][neuronLayer] > 0)])
mpld3.show()
示例2: plot
def plot(self, notebook=False, colormap='polar', scale=1, maptype='points', show=True, savename=None):
# make a spatial map based on the scores
fig = pyplot.figure(figsize=(12, 5))
ax1 = pyplot.subplot2grid((2, 3), (0, 1), colspan=2, rowspan=2)
if maptype is 'points':
ax1, h1 = pointmap(self.scores, colormap=colormap, scale=scale, ax=ax1)
elif maptype is 'image':
ax1, h1 = imagemap(self.scores, colormap=colormap, scale=scale, ax=ax1)
fig.add_axes(ax1)
# make a scatter plot of sampled scores
ax2 = pyplot.subplot2grid((2, 3), (1, 0))
ax2, h2, samples = scatter(self.scores, colormap=colormap, scale=scale, thresh=0.01, nsamples=1000, ax=ax2, store=True)
fig.add_axes(ax2)
# make the line plot of reconstructions from principal components for the same samples
ax3 = pyplot.subplot2grid((2, 3), (0, 0))
ax3, h3, linedata = tsrecon(self.comps, samples, ax=ax3)
plugins.connect(fig, LinkedView(h2, h3[0], linedata))
plugins.connect(fig, HiddenAxes())
if show and notebook is False:
mpld3.show()
if savename is not None:
mpld3.save_html(fig, savename)
elif show is False:
return mpld3.fig_to_html(fig)
示例3: PlotDegreeDistribution
def PlotDegreeDistribution(G):
N = len(G.nodes())
nodesDegrees = [G.degree()[i] for i in G.nodes()]
mean_degree = sum(nodesDegrees)/len(nodesDegrees)
# You typically want your plot to be ~1.33x wider than tall.
# Common sizes: (10, 7.5) and (12, 9)
plt.figure(figsize=(12, 9))
# Remove the plot frame lines. They are unnecessary chartjunk.
ax = plt.subplot(111)
ax.spines["top"].set_visible(False)
ax.spines["right"].set_visible(False)
ax.get_xaxis().tick_bottom()
ax.get_yaxis().tick_left()
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
plt.xlabel("Degree", fontsize=16)
plt.ylabel("Frequency", fontsize=16)
plt.hist(nodesDegrees, color="#3F5D7D") #, bins = [x for x in range(max(nodesDegrees))]) #, bins=100)
xRange = range(max(nodesDegrees))
h = plt.plot(xRange, [m.e**(-mean_degree)*(mean_degree**x)*N/m.factorial(x) for x in xRange], lw=2)
mpld3.show();
示例4: plot
def plot(self, data, notebook=False, show=True, savename=None):
fig = pyplot.figure()
ncenters = len(self.centers)
colorizer = Colorize()
colorizer.get = lambda x: self.colors[int(self.predict(x)[0])]
# plot time series of each center
# TODO move into a time series plotting function in viz.plots
for i, center in enumerate(self.centers):
ax = pyplot.subplot2grid((ncenters, 3), (i, 0))
ax.plot(center, color=self.colors[i], linewidth=5)
fig.add_axes(ax)
# make a scatter plot of the data
ax2 = pyplot.subplot2grid((ncenters, 3), (0, 1), rowspan=ncenters, colspan=2)
ax2, h2 = scatter(data, colormap=colorizer, ax=ax2)
fig.add_axes(ax2)
plugins.connect(fig, HiddenAxes())
if show and notebook is False:
mpld3.show()
if savename is not None:
mpld3.save_html(fig, savename)
elif show is False:
return mpld3.fig_to_html(fig)
示例5: show_plots
def show_plots(plotengine, ax=None, output_dir=None):
if plotengine == 'mpld3':
import mpld3
mpld3.show()
elif plotengine == 'matplotlib':
import matplotlib.pyplot as plt
if not output_dir: # None or ""
plt.show()
else:
for fi in plt.get_fignums():
plt.figure(fi)
fig_name = getattr(plt.figure(fi), 'name', 'figure%d' % fi)
fig_path = op.join(output_dir, '%s.png' % fig_name)
if not op.exists(op.dirname(fig_path)):
os.makedirs(op.dirname(fig_path))
plt.savefig(fig_path)
plt.close()
elif plotengine in ['bokeh', 'bokeh-silent']:
import bokeh.plotting
import tempfile
output_dir = output_dir or tempfile.mkdtemp()
output_name = getattr(ax, 'name', ax.title).replace(':', '-')
output_file = op.join(output_dir, '%s.html' % output_name)
if not op.exists(output_dir):
os.makedirs(output_dir)
if op.exists(output_file):
os.remove(output_file)
bokeh.plotting.output_file(output_file, title=ax.title, mode='inline')
if plotengine == 'bokeh':
bokeh.plotting.show(ax)
示例6: graphme
def graphme(self, pngfilename="my_sample_png.png"):
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import mpld3
import datetime
""" creating background info"""
# create a plot with as may subplots as you choose
fig, ax = plt.subplots()
# add a grid to the background
ax.grid(True, alpha = 0.2)
# the x axis contains date
fig.autofmt_xdate()
# the dates are year, month
ax.fmt_xdata = mdates.DateFormatter('%Y-%m')
if self.table not in ['MS04314', 'MS00114', 'MS04334','MS04315','MS00115']:
final_glitch = self.decide()
dates = sorted(final_glitch.keys())
dates2 = [x for x in dates if final_glitch[x]['mean'] != None and final_glitch[x]['mean'] != "None"]
vals = [final_glitch[x]['mean'] for x in dates2]
glitched_values = ax.plot(dates2, vals, 'b-')
ax.legend(loc=4)
ax.set_xlabel("dates")
ax.set_ylabel("values")
mpld3.show()
mpld3.save_html(fig, 'my_output_html.html')
import pylab
pylab.savefig(pngfilename)
示例7: after
def after(self):
if self.draw:
plugins.connect(
self.fig, plugins.InteractiveLegendPlugin(
self.s1, self.labels, ax=self.ax))
mpld3.show()
else:
pass
示例8: makeFig
def makeFig():
plt.ylim(20,80)
plt.title('Temperature Streaming')
plt.grid(True)
# plt.ylable('Temp C')
plt.plot(tempC, 'ro-',label='Degree C')
plt.legend(loc='upper left')
# pyplot.show_bokeh(plt.gcf(), filename="mpltest.html")
# plotting.session().dumpjson(file="mpltest.json")
mpld3.show()
示例9: do_show
def do_show(self):
#debug
self.debug(
[
'We show here',
'first network'
]
)
#/##################/#
# First network
#
#network all the view things
self.network(
[
'Views',
'Panels',
'Axes',
'Plots'
],
_DoStr='Show'
)
#/##################/#
# Then show the figure
#
#debug
'''
self.debug(
[
'We show with which device',
('self.',self,['ShowingQtBool'])
]
)
'''
#Check
if self.ShowingQtBool:
#import
from matplotlib import pyplot
#show
pyplot.show()
if self.ShowingMpld3Bool:
#import
import mpld3
#show
mpld3.show()
示例10: test_interactive_shallowPP
def test_interactive_shallowPP(save_to_html=False):
# Define left and right state (h,hu)
ql = np.array([3.0, 5.0])
qr = np.array([3.0, -5.0])
# Define optional parameters (otherwise chooses default values)
plotopts = {'g':1.0, 'time':2.0, 'tmax':5, 'hmax':10, 'humin':-15, 'humax':15}
# Call interactive function (can be called without any argument)
pt = shallow_water(ql,qr,**plotopts)
if save_to_html:
mpld3.save_html(pt, "test_shallow.html")
mpld3.show()
示例11: plotter
def plotter(filelist, entlist, fsizelist):
# gets the file and entropy lists and plots the data to a neat line graph
xtimes = [datetime.datetime.strptime(str(int(times)), '%H%M%S') for times in filelist]
plt.plot(fsizelist, entlist, marker='o', color='green')
plt.plot(xtimes, entlist, marker='o')
plt.xlabel('Time')
plt.ylabel('Entropy')
plt.title('Entropy over time for date')
plt.show()
mpld3.show()
return
示例12: main
def main(file_name='Greenland1km.nc'):
'''Description'''
# Set up the file and projection
data = os.path.dirname(os.path.abspath(__file__)) + os.sep + '..' + os.sep \
+ 'data' + os.sep + file_name
proj_file = pyproj.Proj('+proj=stere +ellps=WGS84 +datum=WGS84 +lat_ts=71.0 +lat_0=90 ' \
+ '+lon_0=321.0 +k_0=1.0')
proj_lat_long = pyproj.Proj('+proj=latlong +ellps=WGS84 +datum=WGS84')
fig, ax = plt.subplots(1,2)
# Open up the file and grab the data we want out of it
greenland = Dataset(data)
x = greenland.variables['x'][:]
y = greenland.variables['y'][:]
nx = x.shape[0]
ny = y.shape[0]
y_grid, x_grid = scipy.meshgrid(y[:], x[:], indexing='ij')
thk = greenland.variables['thk'][0]
bheatflx = greenland.variables['bheatflx'][0]
# Now transform the coordinates to the correct lats and lons
lon, lat = pyproj.transform(proj_file, proj_lat_long, x_grid.flatten(), y_grid.flatten())
lat = lat.reshape(ny,nx)
lon = lon.reshape(ny,nx)
# Put thickness in a basemap
mapThk = Basemap(projection='stere',lat_0=65, lon_0=-25,\
llcrnrlat=55,urcrnrlat=85,\
llcrnrlon=-50,urcrnrlon=0,\
rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[0])
mapThk.drawcoastlines(linewidth=0.25)
mapThk.fillcontinents(color='grey')
mapThk.drawmeridians(np.arange(0,360,30))
mapThk.drawparallels(np.arange(-90,90,30))
x, y = mapThk(lon,lat)
cs = mapThk.contour(x, y, thk, 3)
# Put basal heat flux in a basemap
mapFlx = Basemap(projection='stere',lat_0=65, lon_0=-25,\
llcrnrlat=55,urcrnrlat=85,\
llcrnrlon=-50,urcrnrlon=0,\
rsphere=6371200.,resolution='l',area_thresh=10000, ax=ax[1])
mapFlx.drawcoastlines(linewidth=0.25)
mapFlx.fillcontinents(color='grey')
mapFlx.drawmeridians(np.arange(0,360,30))
mapFlx.drawparallels(np.arange(-90,90,30))
x, y = mapFlx(lon,lat)
cs = mapFlx.contour(x, y, bheatflx, 3)
plugins.connect(fig, ClickInfo(cs))
mpld3.show()
示例13: test_interactive_linearPP
def test_interactive_linearPP(save_to_html=False):
## Define left and right state
ql = np.array([-2.0, 2.0])
qr = np.array([0.0, -3.0])
# Define two eigenvectors and eigenvalues (acoustics)
zz = 2.0
rho0 = 1.0
r1 = np.array([zz,1.0])
r2 = np.array([-zz,1.0])
lam1 = zz/rho0
lam2 = -zz/rho0
plotopts={'q1min':-5, 'q1max':5, 'q2min':-5, 'q2max':5, 'domain':5, 'time':1,
'title1':"Pressure", 'title2':"Velocity"}
pt = linear_phase_plane(ql,qr,r1,r2,lam1,lam2,**plotopts)
if save_to_html:
mpld3.save_html(pt, "test_linearPP.html")
mpld3.show()
示例14: plot_engine_timing
def plot_engine_timing(self):
"""
"""
#Import seaborn to prettify the graphs if possible
try:
import seaborn
except:
pass
try:
import matplotlib.pyplot as plt
width = 0.35
s = self.timing['engines'].values()
names = self.timing['engines'].keys()
plt_axes = []
plt_axes_offset = []
for i, n in enumerate(names):
plt_axes.append(i)
plt_axes_offset.append(i + 0.15)
fig, ax = plt.subplots()
rects1 = ax.bar(plt_axes, s, width, color='r')
ax.set_xticks(plt_axes_offset)
ax.set_xticklabels(list(names))
ax.set_ylabel('Time')
ax.set_xlabel('Engine')
plt.title('Timing')
try:
import mpld3
i = 0
for r in rects1:
tooltip = mpld3.plugins.LineLabelTooltip(r, label=names[i])
mpld3.plugins.connect(fig, tooltip)
i = i + 1
mpld3.show()
except Exception as e:
logging.exception(e)
logging.warn("For tooltips, install mpld3 (pip install mpld3)")
plt.show(block=True)
except ImportError:
logging.critical("Cannot plot. Please ensure matplotlib "
"and networkx are installed.")
示例15: main
def main():
# Open the eigenworms file
features_path = os.path.dirname(mv.features.__file__)
eigenworm_path = os.path.join(features_path, mv.config.EIGENWORM_FILE)
eigenworm_file = h5py.File(eigenworm_path, 'r')
# Extract the data
eigenworms = eigenworm_file["eigenWorms"].value
eigenworm_file.close()
# Print the shape of eigenworm matrix
print(np.shape(eigenworms))
# Plot the eigenworms
for eigenworm_i in range(np.shape(eigenworms)[1]):
plt.plot(eigenworms[:,eigenworm_i])
mpld3.show()