本文整理汇总了Python中mpld3.show函数的典型用法代码示例。如果您正苦于以下问题:Python show函数的具体用法?Python show怎么用?Python show使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了show函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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()
开发者ID:raventyrr,项目名称:net-vizz,代码行数:32,代码来源:print_NN.py
示例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)
开发者ID:mathisonian,项目名称:thunder,代码行数:30,代码来源:pca.py
示例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();
开发者ID:kojino,项目名称:cs136-final_project,代码行数:28,代码来源:plotting.py
示例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)
开发者ID:uklibaite,项目名称:thunder,代码行数:30,代码来源:kmeans.py
示例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)
开发者ID:bcipolli,项目名称:PING,代码行数:34,代码来源:plotting.py
示例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)
开发者ID:tinybike,项目名称:glitch,代码行数:32,代码来源:logic_glitch.py
示例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
开发者ID:ssh0,项目名称:sotsuron,代码行数:8,代码来源:simple3.py
示例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()
开发者ID:ari-analytics,项目名称:myPython,代码行数:10,代码来源:tempc.py
示例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()
开发者ID:BinWang20140601,项目名称:ShareYourSystem,代码行数:55,代码来源:__init__.py
示例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()
开发者ID:BrisaDavis,项目名称:riemann,代码行数:11,代码来源:riemann_interactive.py
示例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
开发者ID:severagee,项目名称:Bee-GUI-WebApp,代码行数:12,代码来源:app.py
示例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()
开发者ID:arbennett,项目名称:Greenland_Interacts,代码行数:52,代码来源:greenland_interacts.py
示例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()
开发者ID:BrisaDavis,项目名称:riemann,代码行数:17,代码来源:riemann_interactive.py
示例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.")
开发者ID:UMWRG,项目名称:pynsim,代码行数:46,代码来源:simulator.py
示例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()
开发者ID:ravibajaj,项目名称:movement_validation,代码行数:18,代码来源:plot_eigenworms.py
示例16: plot_d3js
def plot_d3js():
# Define some CSS to control our custom labels
css = """
table
{
border-collapse: collapse;
}
th
{
color: #ffffff;
background-color: #000000;
}
td
{
background-color: #cccccc;
}
table, th, td
{
font-family:Arial, Helvetica, sans-serif;
border: 1px solid black;
text-align: right;
}
"""
fig, ax = plt.subplots()
ax.grid(True, alpha=0.3)
labels = suburb_list
x = coords[:, 0]
y = coords[:, 1]
points = ax.plot(x, y, 'o', color='b',
mec='k', ms=15, mew=1, alpha=.6)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('Ethnicity', size=20)
tooltip = plugins.PointHTMLTooltip(points[0], labels,
voffset=10, hoffset=10, css=css)
plugins.connect(fig, tooltip)
mpld3.show()
开发者ID:xpendous,项目名称:statistical_machine_learning,代码行数:42,代码来源:diversity.py
示例17: plot_team
def plot_team(sorted_team, sorted_teamgames):
fig = plt.figure(figsize=(12, 12))
#ax = fig.add_axes([0.15, 0.1, 0.7, 0.7])
grid = ImageGrid(fig,
(0.2, 0.15, 0.8, 0.8),
#111,
nrows_ncols=(1, 1),
direction='row', axes_pad=0.05, add_all=True,
label_mode='1', share_all=False,
cbar_location='right', cbar_mode='single',
cbar_size='5%', cbar_pad=0.05)
ax = grid[0]
ax.set_title('Game lead (each team is a column)', fontsize=20)
ax.tick_params(axis='both', direction='out', labelsize=12)
#im = ax.imshow(df.values, interpolation='nearest', vmax=df.max().max(),
# vmin=df.min().min(), cmap='RdBu')
im = ax.imshow(sorted_teamgames.values, interpolation='nearest', vmax=120, vmin=-120, cmap='RdBu')
#colorbar
ax.cax.colorbar(im)
ax.cax.tick_params(labelsize=12)
ax.set_xticks(np.arange(sorted_teamgames.shape[1]))
ax.set_xticklabels(sorted_team, rotation='vertical', fontweight='bold')
ax.set_yticks(np.arange(sorted_teamgames.shape[0]))
ax.set_yticklabels(sorted_teamgames.index)
ax.set_ylabel("Sorted game", size=16)
#plt.show()
plotid = mpld3.utils.get_id(ax)
print sorted_team
ax_ori = RotateTick(0, sorted_team.tolist(), -90, 1,1)
mpld3.plugins.connect(fig, ax_ori)
mpld3.show()
fightml = mpld3.fig_to_html(fig)
return plotid, fightml
开发者ID:jinghuage,项目名称:pythonwebapp-aflvis,代码行数:40,代码来源:aflstatsgraph.py
示例18: make_optional_graphs
def make_optional_graphs(wd):
""" A function that can be called to graph the difference method against the ratio method if necessary.
Do not need in production, but used for testing on 10-1-2015 to see if we can get to the values working as Don expects
:wd: the dictionary containing adjustments etc used to figure out the final csv
"""
if wd != {} and wd[wd.keys()[0]]['adj_diff'] != None and wd[wd.keys()[0]]['adj_rat'] != None:
datelist = [x for x in sorted(wd.keys()) if wd[x]['adj_rat'] != None and wd[x]['adj_diff'] != None]
val_diff = [wd[x]['adj_diff'] for x in datelist]
val_rat = [wd[x]['adj_rat'] for x in datelist]
fig, ax = plt.subplots()
fig.autofmt_xdate()
ax.fmt_xdata = mdates.DateFormatter('%Y-%m')
ax.plot(datelist, val_diff, color = 'blue', linewidth= 1.2, alpha = 0.5, label = 'diff method')
ax.plot(datelist, val_rat, color = 'red', linewidth= 0.7, label = 'ratio method')
#ax.scatter(mainte_dates, maintes, s=30, c='red', alpha = 0.4, label='MAINTE')
ax.legend(loc = 1)
mpld3.show()
开发者ID:dataRonin,项目名称:weir2k,代码行数:22,代码来源:weir2k.py
示例19: plotData
def plotData(NQuery, input_table, FigureStrBase, html_dir=None, png_dir=None,
xvariable='SurfaceDensity', yvariable='VelocityDispersion',
zvariable='Radius',
xMin=None, xMax=None, yMin=None, yMax=None, zMin=None, zMax=None,
interactive=False, show_log=True, min_marker_width=3,
max_marker_width=0.05):
"""
This is where documentation needs to be added
Parameters
----------
NQuery
FigureStrBase : str
The start of the output filename, e.g. for "my_file.png" it would be
my_file
xMin
xMax
yMin
yMax
zMin
zMax
min_marker_width : int or float, optional
Sets the pixel width of the smallest marker to be plotted. If <1,
it is interpreted to be a fraction of the total pixels along the
shortest axis.
max_marker_width : int or float, optional
Sets the pixel width of the smallest marker to be plotted. If <1,
it is interpreted to be a fraction of the total pixels along the
shortest axis.
"""
if len(input_table) == 0:
raise ValueError("The input table is empty.")
figure = matplotlib.figure.Figure()
if interactive:
from matplotlib import pyplot
from matplotlib import _pylab_helpers
backend = getattr(matplotlib.backends, 'backend_{0}'.format(matplotlib.rcParams['backend']).lower())
canvas = backend.FigureCanvas(figure)
figmanager = backend.FigureManager(canvas, 1)
figmanager.canvas.figure.number = 1
_pylab_helpers.Gcf.set_active(figmanager)
else:
figure = matplotlib.figure.Figure()
canvas = FigureCanvasAgg(figure)
ax = figure.gca()
d = input_table
Author = d['Names']
Run = d['IDs']
x_ax = d[xvariable]
y_ax = d[yvariable]
z_ax = d[zvariable]
# Check if limits are given
if xMin is None:
xMin = x_ax.min()
if xMax is None:
xMax = x_ax.max()
if yMin is None:
yMin = y_ax.min()
if yMax is None:
yMax = y_ax.max()
if zMin is None:
zMin = z_ax.min()
if zMax is None:
zMax = z_ax.max()
if d['IsSimulated'].dtype == 'bool':
IsSim = d['IsSimulated']
else:
IsSim = d['IsSimulated'] == 'True'
if show_log:
if not label_dict_html[xvariable].startswith('log'):
label_dict_html[xvariable] = 'log ' + label_dict_html[xvariable]
label_dict_html[yvariable] = 'log ' + label_dict_html[yvariable]
if not label_dict_png[xvariable].startswith('log'):
label_dict_png[xvariable] = 'log ' + label_dict_png[xvariable]
label_dict_png[yvariable] = 'log ' + label_dict_png[yvariable]
# Select points within the limits
Use_x_ax = (x_ax > xMin) & (x_ax < xMax)
Use_y_ax = (y_ax > yMin) & (y_ax < yMax)
Use_z_ax = (z_ax > zMin) & (z_ax < zMax)
# intersects the three subsets defined above
Use = Use_x_ax & Use_y_ax & Use_z_ax
nptstoplot = np.count_nonzero(Use)
if nptstoplot == 0:
log.debug("Use: {0}".format(Use))
log.debug("Use_x_ax: {0}".format(Use_x_ax))
log.debug("xmin: {0} xmax: {1}".format(xMin, xMax))
log.debug("x_ax: {0}".format(x_ax))
log.debug("Use_y_ax: {0}".format(Use_y_ax))
log.debug("ymin: {0} ymax: {1}".format(yMin, yMax))
log.debug("y_ax: {0}".format(y_ax))
#.........这里部分代码省略.........
开发者ID:adamginsburg,项目名称:frontend,代码行数:101,代码来源:simple_plot.py
示例20: plot_2d_graph
#.........这里部分代码省略.........
if gp.line_of_best_fit == True:
self.trendline(ax_temp, xd.values, yd.values, order=1, color= color_spec, alpha=1,
scale_factor = scale_factor)
except: pass
# format X axis
self.format_x_axis(ax, data_frame, gp)
try:
fig.suptitle(gp.title, fontsize = 14 * scale_factor)
except: pass
try:
source = Constants().plotfactory_source
source_color = 'black'
display_brand_label = False
if hasattr(gp, 'source'):
source = gp.source
display_brand_label = True
if hasattr(gp, 'source_color'):
source_color = self.get_color_code(gp.source_color)
if display_brand_label or Constants().plotfactory_display_brand_label:
ax.annotate('Source: ' + source, xy = (1, 0), xycoords='axes fraction', fontsize=7 * scale_factor,
xytext=(-5 * scale_factor, 10 * scale_factor), textcoords='offset points',
ha='right', va='top', color = source_color)
except: pass
if hasattr(gp, 'display_brand_label'):
if gp.display_brand_label is True:
self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = scale_factor)
else:
if Constants().plotfactory_display_brand_label is True:
self.create_brand_label(ax, anno = Constants().plotfactory_brand_label, scale_factor = scale_factor)
leg = []
leg2 = []
loc = 'best'
# if we have two y-axis then make sure legends are in opposite corners
if ax2 != []: loc = 2
try:
leg = ax.legend(loc = loc, prop={'size':10 * scale_factor})
leg.get_frame().set_linewidth(0.0)
leg.get_frame().set_alpha(0)
if ax2 is not []:
leg2 = ax2.legend(loc = 1, prop={'size':10 * scale_factor})
leg2.get_frame().set_linewidth(0.0)
leg2.get_frame().set_alpha(0)
except: pass
try:
if gp.display_legend == False:
if leg is not[]: leg.remove()
if leg2 is not[]: leg.remove()
except: pass
try:
plt.savefig(gp.file_output, transparent=False)
except: pass
try:
if hasattr(gp, 'silent_display'):
if gp.silent_display is False:
plt.show()
else:
plt.show()
except:
pass
# convert to D3 format with mpld3
try:
if hasattr(gp, 'html_file_output'):
mpld3.save_d3_html(fig, gp.html_file_output)
if hasattr(gp, 'display_mpld3'):
if gp.display_mpld3 == True: mpld3.show(fig)
except: pass
# convert to Plotly format (fragile!)
# TODO better to create Plotly graphs from scratch rather than convert from matplotlib
# TODO also dependent on matplotlib version for support
try:
if hasattr(gp, 'plotly_url'):
plotly.tools.set_credentials_file(username = Constants().plotly_username,
api_key = Constants().plotly_api_key)
py_fig = tls.mpl_to_plotly(fig, strip_style = True)
plot_url = py.plot_mpl(py_fig, filename = gp.plotly_url)
except:
pass
开发者ID:AlexColson,项目名称:pythalesians,代码行数:101,代码来源:adapterpythalesians.py
注:本文中的mpld3.show函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论