本文整理汇总了Python中mpld3.fig_to_dict函数的典型用法代码示例。如果您正苦于以下问题:Python fig_to_dict函数的具体用法?Python fig_to_dict怎么用?Python fig_to_dict使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fig_to_dict函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: pcaPlot
def pcaPlot():
print 1
json = request.get_json()
# lists=[]
# for row in json:
# aa=[row["Open"],row["Close"],row["Change"],row["Volume"]]
# #print aa
# lists.append(aa)
print 2
x=colorArray(json["clusters"])
a= np.array(json["result"]).astype(np.float)
fig=plt.figure()
dims=random.sample(range(0, 3), 2)
plt.scatter(a[:,dims[0]],a[:,dims[1]], c=x)
plt.xlabel('x_values')
plt.ylabel('y_values')
plt.xlim([-4,4])
plt.ylim([-4,4])
plt.title('Scree Plot of PCA')
# X_iso = manifold.Isomap(10, n_components=2).fit_transform(mlab_pca.Y)
# #mpld3.show()
# print mpld3.fig_to_dict(fig)
return jsonify(result=mpld3.fig_to_dict(fig))
开发者ID:huntriver,项目名称:CSE-564-Proj2,代码行数:30,代码来源:app.py
示例2: chart_template_direct
def chart_template_direct(request, disease_id, state_id):
return HttpResponse(request_url)
js_data = json.dumps(mpld3.fig_to_dict(fig))
return render_to_response('direct_plot.html', {"my_data": js_data})
开发者ID:SwampGuzzler,项目名称:django-charts,代码行数:7,代码来源:views.py
示例3: api_activity_histogram
def api_activity_histogram(self,app_id,exp_uid,task):
"""
Description: returns the data to plot all API activity (for all algorithms) in a histogram with respect to time for any task in {getQuery,processAnswer,predict}
Expected input:
(string) task : must be in {'getQuery','processAnswer','predict'}
Expected output (in dict):
(dict) MPLD3 plot dictionary
"""
list_of_log_dict,didSucceed,message = self.ell.get_logs_with_filter(app_id+':APP-CALL',{'exp_uid':exp_uid,'task':task})
from datetime import datetime
from datetime import timedelta
start_date_str,didSucceed,message = self.db.get('experiments_admin',exp_uid,'start_date')
start_date = utils.str2datetime(start_date_str)
numerical_timestamps = [ ( utils.str2datetime(item['timestamp'])-start_date).total_seconds() for item in list_of_log_dict]
import matplotlib.pyplot as plt
import mpld3
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#FFFFFF'),figsize=(12,1.5))
ax.hist(numerical_timestamps,int(1+4*numpy.sqrt(len(numerical_timestamps))),alpha=0.5,color='black')
ax.set_frame_on(False)
ax.get_xaxis().set_ticks([])
ax.get_yaxis().set_ticks([])
ax.get_yaxis().set_visible(False)
ax.set_xlim(0, max(numerical_timestamps))
plot_dict = mpld3.fig_to_dict(fig)
return plot_dict
开发者ID:NandanaSengupta,项目名称:NEXT,代码行数:33,代码来源:AppDashboard.py
示例4: run
def run(self):
# Pass DataFrame itself into task?
# Pointless to read url, write to csv, then read csv
alertsdata = pandas.read_csv(self.input().path)
alertsdata.columns = [x.replace('#','').strip().lower() for x in alertsdata.columns.values.tolist()]
ra = np.array(alertsdata['radeg'])
dec = np.array(alertsdata['decdeg'])
mag = np.array(alertsdata['alertmag'])
alclass = np.array(alertsdata['class'])
cmap = mpl.cm.rainbow
classes = list(set(alclass))
colours = {classes[i]: cmap(i / float(len(classes))) for i in range(len(classes))}
fig = plt.figure()
for i in range(len(ra)):
plt.plot(ra[i], dec[i], 'o', ms=self.magtopoint(mag[i], mag), color=colours[alclass[i]])
plt.xlabel('Right Ascension')
plt.ylabel('Declination')
with open(self.output().path, 'w') as out:
json.dump(mpld3.fig_to_dict(fig), out)
开发者ID:parameterspace-ie,项目名称:example-avi-alerts,代码行数:26,代码来源:tasks.py
示例5: network_delay_histogram
def network_delay_histogram(self, app, butler, alg_label):
"""
Description: returns the data to network delay histogram of the time it takes to getQuery+processAnswer for each algorithm
Expected input:
(string) alg_label : must be a valid alg_label contained in alg_list list of dicts
Expected output (in dict):
(dict) MPLD3 plot dictionary
"""
list_of_query_dict,didSucceed,message = self.db.get_docs_with_filter(app.app_id+':queries',{'exp_uid':app.exp_uid,'alg_label':alg_label})
t = []
for item in list_of_query_dict:
try:
t.append(item['network_delay'])
except:
pass
fig, ax = plt.subplots(subplot_kw=dict(axisbg='#FFFFFF'))
ax.hist(t,MAX_SAMPLES_PER_PLOT,range=(0,5),alpha=0.5,color='black')
ax.set_xlim(0, 5)
ax.set_axis_off()
ax.set_xlabel('Durations (s)')
ax.set_ylabel('Count')
ax.set_title(alg_label + " - network delay", size=14)
plot_dict = mpld3.fig_to_dict(fig)
plt.close()
return plot_dict
开发者ID:dconathan,项目名称:NEXT,代码行数:30,代码来源:AppDashboard.py
示例6: update_figure
def update_figure(self, rnd_draws):
# regenerate matplotlib plot
self.ax1.cla()
self.ax1.set_xlabel('r1')
self.ax1.set_ylabel('Normalized Distribtuion')
self.ax1.set_xlim(0, 1)
self.ax1.set_ylim(0, 1.5)
self.ax1.grid(True)
self.ax1.hist(
[r[0] for r in rnd_draws], 50,
normed=1, facecolor='green', alpha=0.75
)
self.ax2.cla()
self.ax2.set_xlabel('r2')
self.ax2.set_ylabel('Normalized Distribtuion')
self.ax2.set_xlim(0, 1)
self.ax2.set_ylim(0, 1.5)
self.ax2.grid(True)
self.ax2.hist(
[r[1] for r in rnd_draws], 50,
normed=1, facecolor='blue', alpha=0.75
)
# send new matplotlib plots to frontend
self.emit('mpld3canvas', mpld3.fig_to_dict(self.fig))
开发者ID:acactown,项目名称:databench_examples,代码行数:25,代码来源:analysis.py
示例7: plot_grid_3d
def plot_grid_3d(X_range, Y_range, Z, X_label='X', Y_label='Y', Z_label='Z', json_data=False):
fig = plt.figure(figsize=(18,6))
ax = fig.add_subplot(1, 1, 1, projection='3d')
X, Y = np.meshgrid(X_range, Y_range)
Zm = Z #zip(*Z)
# print "[plot_check]", np.shape(X_range), np.shape(Y_range), np.shape(X), np.shape(Y), np.shape(Z)
p = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm, linewidth=0, antialiased=False)
x_offset = (max(X_range) - min(X_range))*0.2
y_offset = (max(Y_range) - min(Y_range))*0.2
Zmax = max(max(Zm))
Zmin = min(min(Zm))
z_offset = (Zmax - Zmin)*0.2
cset = ax.contour(X, Y, Z, zdir='x', offset=X_range[0]-x_offset, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=Y_range[-1]+y_offset, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='z', offset=Zmin-z_offset, cmap=cm.coolwarm)
ax.set_xlabel(X_label)
ax.set_ylabel(Y_label)
ax.set_zlabel(Z_label)
ax.set_xlim(X_range[0]-x_offset, X_range[-1])
ax.set_ylim(Y_range[0], Y_range[-1]+y_offset)
ax.set_zlim(Zmin-z_offset, Zmax+z_offset)
cb = fig.colorbar(p, shrink=0.5)
# print "[mpld3] before json serialize."
if json_data: return mpld3.fig_to_dict(fig)
开发者ID:Marsan-Ma,项目名称:adminer,代码行数:25,代码来源:svr_plot.py
示例8: pcaGraph
def pcaGraph():
json = request.get_json()
# lists=[]
# for row in json:
# aa=[row["Open"],row["Close"],row["Change"],row["Volume"]]
# #print aa
# lists.append(aa)
x=colorArray(json["clusters"])
a= np.array(json["result"]).astype(np.float)
# print a
fig=plt.figure()
plt.scatter(a[:,0],a[:,1], c=x)
plt.xlabel('x_values')
plt.ylabel('y_values')
plt.xlim([-4,4])
plt.ylim([-4,4])
plt.title('PCA Graph')
# X_iso = manifold.Isomap(10, n_components=2).fit_transform(mlab_pca.Y)
# mpld3.show()
# print mpld3.fig_to_dict(fig)
return jsonify(result=mpld3.fig_to_dict(fig))
开发者ID:huntriver,项目名称:CSE-564-Proj2,代码行数:27,代码来源:app.py
示例9: mdsGraph
def mdsGraph():
json = request.get_json()
# lists=[]
# for row in json:
# aa=[row["Open"],row["Close"],row["Change"],row["Volume"]]
# #print aa
# lists.append(aa)
# x =[]
# clusters=json["clusters"]
# tmp=[0]*clusters[0]
# x.extend(tmp)
# tmp=[50]*clusters[1]
# x.extend(tmp)
# tmp=[100]*clusters[2]
# x.extend(tmp)
# x=np.array(x)
x=colorArray(json["clusters"])
a= np.array(json["result"]).astype(np.float)
Y = manifold.MDS(2 , max_iter=100, n_init=4).fit_transform(a)
fig=plt.figure()
plt.scatter(Y[:,0],Y[:,1],c=x)
plt.xlabel('x_values')
plt.ylabel('y_values')
plt.xlim([-4,4])
plt.ylim([-4,4])
plt.title('MDS Graph')
# X_iso = manifold.Isomap(10, n_components=2).fit_transform(mlab_pca.Y)
# #mpld3.show()
# print mpld3.fig_to_dict(fig)
return jsonify(result=mpld3.fig_to_dict(fig))
开发者ID:huntriver,项目名称:CSE-564-Proj2,代码行数:35,代码来源:app.py
示例10: _plot_figure
def _plot_figure(self, idx):
from .display_hooks import display_frame
self.plot.update(idx)
if OutputMagic.options['backend'] == 'd3':
import mpld3
mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fontsize=14))
return mpld3.fig_to_dict(self.plot.state)
return display_frame(self.plot, **self.display_options)
开发者ID:cmiller8,项目名称:holoviews,代码行数:8,代码来源:widgets.py
示例11: _plot_figure
def _plot_figure(self, idx):
from .display_hooks import display_figure
fig = self.plot[idx]
if OutputMagic.options['backend'] == 'd3':
import mpld3
mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fontsize=14))
return mpld3.fig_to_dict(fig)
return display_figure(fig)
开发者ID:sehahn,项目名称:holoviews,代码行数:8,代码来源:widgets.py
示例12: get_statistics_rasterplot
def get_statistics_rasterplot(videoname, runname):
with Run(videoname, runname) as run:
run['time_per_bin'] = float(request.form['time_per_bin'])
fig_raster = analyzer.plot.plot_rasterplot(run['statistics']['spikes'],
run['exposure_time'],
run['time_per_bin'])
rasterplot = mpld3.fig_to_dict(fig_raster)
return jsonify(rasterplot=rasterplot)
开发者ID:Moschn,项目名称:neuronal-activity-analyzer,代码行数:9,代码来源:statistics.py
示例13: on_run
def on_run(self):
"""Run when button is pressed."""
self.emit('log', 'Hi. The run button was pressed. Going to sleep.')
time.sleep(self.sleep_duration)
self.emit('log', 'Waking up again. Run is done.')
# draw something on self.fig
# regenerate matplotlib plot
self.ax.cla()
self.ax.set_xlabel('output of random.random()')
self.ax.set_ylabel('normalized distribtuion of 100 trials')
self.ax.set_xlim(0, 1)
self.ax.set_ylim(0, 1.5)
self.ax.grid(True)
self.ax.hist(
[random.random() for i in xrange(100)], 5,
normed=1, facecolor='green', alpha=0.75
)
self.emit('mpld3canvas', mpld3.fig_to_dict(self.fig))
# create the data for the Basic d3.js part
data = [
{'id': 1, 'x1': 0.1, 'y1': 0.1, 'x2': 0.8, 'y2': 0.5,
'width': 0.05, 'color': 0.5},
{'id': 2, 'x1': 0.1, 'y1': 0.3, 'x2': 0.8, 'y2': 0.7,
'width': 0.05, 'color': 0.7},
{'id': 3, 'x1': 0.1, 'y1': 0.5, 'x2': 0.8, 'y2': 0.9,
'width': 0.05, 'color': 0.9},
]
self.emit('update_basic', data)
# update with some new data after a short wait
time.sleep(1)
data2 = [
{'id': 1, 'x1': 0.1, 'y1': 0.1, 'x2': 0.8, 'y2': 0.5,
'width': 0.2, 'color': 0.5},
{'id': 2, 'x1': 0.1, 'y1': 0.3, 'x2': 0.8, 'y2': 0.7,
'width': 0.2, 'color': 0.7},
{'id': 3, 'x1': 0.1, 'y1': 0.5, 'x2': 0.8, 'y2': 0.9,
'width': 0.2, 'color': 0.9},
]
self.emit('update_basic', data2)
# create and send data for the d3.js plot
self.emit('log', 'Increasing numbers.')
self.emit('update_plot', [0.1, 0.3, 0.5, 0.7, 0.9])
time.sleep(1)
self.emit('log', 'Random numbers.')
self.emit('update_plot', [random.random() for i in xrange(5)])
time.sleep(1)
# Animation of a sin wave. Use numpy.
self.emit('log', 'Animate a sin wave.')
x = numpy.linspace(0, numpy.pi, 5)
for t in xrange(50):
numpy_data = 0.5 + 0.4*numpy.sin(x + t/3.0)
self.emit('update_plot', numpy_data.tolist())
time.sleep(0.25)
开发者ID:pombredanne,项目名称:databench_examples,代码行数:56,代码来源:analysis.py
示例14: plot_grid_2d
def plot_grid_2d(X, Z, X_label='X', Z_label='Z', json_data=False):
fig = plt.figure(figsize=(6,2.5))
ax = fig.add_subplot(1, 1, 1)
p = ax.plot(X, Z)
ax.set_xlabel(X_label)
ax.set_ylabel(Z_label)
if json_data:
chart_data = mpld3.fig_to_dict(fig)
plt.close()
return chart_data
开发者ID:Marsan-Ma,项目名称:adminer,代码行数:10,代码来源:svr_plot.py
示例15: viz_content
def viz_content():
params = get_params(request)
df = get_events_by_content(g.db_engine, params)
ax = df.plot(x='loaded', y='played', kind='scatter', figsize=(12, 8))
mpld3_data = mpld3.fig_to_dict(ax.get_figure())
url_format = lambda x: '<a href="%s">%s</a>' % (x, x)
table_html = df.head(20).to_html(classes=['table'], formatters={'content_url': url_format})
return render_template('base_viz.html', \
clients=get_clients(), content_hosts=get_content_hosts(), params=params, \
data_table=table_html, mpld3_data=json.dumps(mpld3_data))
开发者ID:sampathweb,项目名称:insight-embedly,代码行数:10,代码来源:main.py
示例16: home
def home(request):
context = {}
context['requestMethod'] = request.META['REQUEST_METHOD']
if request.method == 'GET' :
if request.GET.__contains__('hidden') :
#if 'name' in context and 'end_date' in context and 'start_date' in context:
context['name'] = request.GET['name']
context['start_date'] = request.GET['start_date']
context['end_date'] = request.GET['end_date']
print context
requestContext = RequestContext(request, context)
templateIndex = loader.get_template('index.html')
renderedTemplate = templateIndex.render(requestContext)
response = HttpResponse()
response['Age'] = 120
response.write(renderedTemplate)
if 'name' in context:# and 'end_date' in context and 'start_date' in context:
company = context['name'].encode('ascii','ignore')
start_date = context['start_date'].encode('ascii','ignore')
end_date = context['end_date'].encode('ascii','ignore')
a = request.GET.get('name')
start_date = start_date.split('-')
end_date = end_date.split('-')
start = datetime.datetime(int(start_date[0]),int(start_date[1]),int(start_date[2]))
end = datetime.datetime(int(end_date[0]),int(end_date[1]),int(end_date[2]))
f = web.DataReader(company,'yahoo',start,end)
a = f['Close']
b = a.index.tolist()
array = []
for i in range(b.__len__()):
c = b[i]
s = str(c)[:10]
d = a.tolist()
e = round(d[i],2)
array.append(e)
#print f
fig = figure(1)
plot([3,1,2,4,1])
js_data = json.dumps(mpld3.fig_to_dict(fig))
return render_to_response('index.html',{'array':json.dumps(array), 'start_date':json.dumps(start_date), 'end_date':json.dumps(end_date), 'js_data': js_data})
return render_to_response('index.html',{})
开发者ID:ZhuoranLyu,项目名称:Programming-for-DS,代码行数:54,代码来源:views.py
示例17: viz_date
def viz_date():
params = get_params(request)
df = get_events_date_df(g.db_engine, params)
df = df.unstack(1)
ax = df.plot(legend=['load', 'play'], figsize=(12, 8))
ax.set_xlabel('Date')
mpld3_data = mpld3.fig_to_dict(ax.get_figure())
table_df = get_events_by_source_df(g.db_engine, params)
ratio_format = lambda x: '<span class="significant"><bold>%f</bold></span>' % x
table_html = table_df.head(20).to_html(classes=['table'], formatters={'ratio': ratio_format})
return render_template('base_viz.html', \
clients=get_clients(), content_hosts=get_content_hosts(), params=params, \
data_table=table_html, mpld3_data=json.dumps(mpld3_data))
开发者ID:sampathweb,项目名称:insight-embedly,代码行数:13,代码来源:main.py
示例18: vis_rec
def vis_rec(data, fig_id, title=None):
data = data.copy()
data -= data.min()
data /= data.max()
plt.figure()
plt.xticks(np.arange(0, 10, 1.0))
plt.yticks([])
plt.imshow(data)
if title:
plt.title(title)
plt.tight_layout()
return {'id': fig_id, 'json': json.dumps(mpld3.fig_to_dict(plt.gcf()))}
开发者ID:danielhers,项目名称:caffe,代码行数:14,代码来源:app.py
示例19: show_plot_shear
def show_plot_shear(span_length, x_loc, feet_or_frac, max_shear_loc):
axle_pos = max_shear_loc
x_loc = x_loc * span_length if feet_or_frac == 'frac' else x_loc
# Plot span
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
span = ax.plot([0, span_length], [0, 0], 'b')
# Add boundaries to span
# tri_width = (span_length*1.2+20)/120
# bound1 = plt.plot([0, -tri_width, tri_width, 0], [0, -2, -2, 0])
bound1 = ax.plot(0, -0.7, 'b^')
bound2 = ax.plot(span_length, -0.7, 'bo')
axle_pos += span_length
# Cooper E-80 Axle Layout
axle_loads = [40, 80, 80, 80, 80, 52, 52, 52, 52,
40, 80, 80, 80, 80, 52, 52, 52, 52,
8]
axle_spaces = [0, 8, 5, 5, 5, 9, 5, 6, 5,
8, 8, 5, 5, 5, 9, 5, 6, 5,
5.5]
train_len = sum(axle_spaces)
while (sum(axle_spaces) - train_len) < span_length:
axle_spaces.append(1)
axle_loads.append(8)
for pos, spac in enumerate(axle_spaces):
axle_pos = axle_pos - spac
axle_load = 1 + axle_loads[pos] / 4
axle = ax.plot([axle_pos, axle_pos], [1, axle_load], 'r')
axle_label = ax.text(axle_pos - 1.5,
axle_load + 2,
str(axle_loads[pos]) + 'k',
fontsize=8,
color='r')
axle_end = ax.plot(axle_pos, 1, 'rv')
xplot = ax.plot([x_loc, x_loc], [-1, -5], 'y')
xplotarr = ax.plot(x_loc, -1 ,'y^')
ax.set_xlim(-20, span_length + 20)
ax.set_ylim(-30, 60)
ax.set_title('Train Position for Max Shear')
return mpld3.fig_to_dict(fig)
开发者ID:rspears74,项目名称:my-site,代码行数:49,代码来源:mvbridge.py
示例20: _figure_data
def _figure_data(self, plot, fmt='png', bbox_inches='tight', **kwargs):
"""
Render matplotlib figure object and return the corresponding data.
Similar to IPython.core.pylabtools.print_figure but without
any IPython dependency.
"""
fig = plot.state
if self.mode == 'nbagg':
manager = self.get_figure_manager(plot.state)
if manager is None: return ''
self.counter += 1
manager.show()
return ''
elif self.mode == 'mpld3':
import mpld3
fig.dpi = self.dpi
mpld3.plugins.connect(fig, mpld3.plugins.MousePosition(fontsize=14))
if fmt == 'json':
return mpld3.fig_to_dict(fig)
else:
return "<center>" + mpld3.fig_to_html(fig) + "<center/>"
traverse_fn = lambda x: x.handles.get('bbox_extra_artists', None)
extra_artists = list(chain(*[artists for artists in plot.traverse(traverse_fn)
if artists is not None]))
kw = dict(
format=fmt,
facecolor=fig.get_facecolor(),
edgecolor=fig.get_edgecolor(),
dpi=self.dpi,
bbox_inches=bbox_inches,
bbox_extra_artists=extra_artists
)
kw.update(kwargs)
# Attempts to precompute the tight bounding box
try:
kw = self._compute_bbox(fig, kw)
except:
pass
bytes_io = BytesIO()
fig.canvas.print_figure(bytes_io, **kw)
data = bytes_io.getvalue()
if fmt == 'svg':
data = data.decode('utf-8')
return data
开发者ID:corinnebosley,项目名称:holoviews,代码行数:49,代码来源:renderer.py
注:本文中的mpld3.fig_to_dict函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论