def _determine_mpld3ids(self, plot_elements): """ Helper function to get the mpld3_id for each of the specified elements. """ mpld3_element_ids = [] # There are two things being done here. First, # we make sure that we have a list of lists, where # each inner list is associated with a single legend # item. Second, in case of Line2D object we pass # the id for both the marker and the line. # on the javascript side we filter out the nulls in # case either the line or the marker has no equivalent # D3 representation. for entry in plot_elements: ids = [] if isinstance(entry, collections.Iterable): for element in entry: mpld3_id = get_id(element) ids.append(mpld3_id) if isinstance(element, matplotlib.lines.Line2D): mpld3_id = get_id(element, 'pts') ids.append(mpld3_id) else: ids.append(get_id(entry)) if isinstance(entry, matplotlib.lines.Line2D): mpld3_id = get_id(entry, 'pts') ids.append(mpld3_id) mpld3_element_ids.append(ids) return mpld3_element_ids
def __init__(self, points, line, linedata, line2, linedata2): self.dict_ = {"type": "clickinfo", "idpts": utils.get_id(points), "idline": utils.get_id(line), "data": linedata, "idline2": utils.get_id(line2), "data2": linedata2}
def _determine_mpld3ids(self, plot_elements): """ Helper function to get the mpld3_id for each of the specified elements. This is a convenience function. You can now do: lines = ax.plot(x,y) plugins.connect(fig, HighlightLines(lines, labels)) rather than first having to wrap each entry in lines in a seperate list. """ mpld3_element_ids = [] for entry in plot_elements: if isinstance(entry, collections.Iterable): mpld3_element_ids.append( [utils.get_id(element) for element in entry]) else: mpld3_element_ids.append([utils.get_id(entry)]) return mpld3_element_ids
def _determine_mpld3ids(self, plot_elements): """ Helper function to get the mpld3_id for each of the specified elements. This is a convenience function. You can now do: lines = ax.plot(x,y) plugins.connect(fig, HighlightLines(lines, labels)) rather than first having to wrap each entry in lines in a seperate list. """ mpld3_element_ids = [] for entry in plot_elements: if isinstance(entry, collections.Iterable): mpld3_element_ids.append([utils.get_id(element) for element in entry]) else: mpld3_element_ids.append([utils.get_id(entry)]) return mpld3_element_ids
def __init__(self, p, l): self.dict_ = { "type": "clickinfo", "id": [utils.get_id(i) for i in p], "labels": l } print([utils.get_id(i) for i in p])
def __init__(self, pendulum, trajectory): self.dict_ = { "type": "animatependulum", "idpendulum": utils.get_id(pendulum), "idtrajectory": utils.get_id(trajectory) }
def __init__(self, points, line, linedata): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "linkedview", "idpts": utils.get_id(points, suffix), "idline": utils.get_id(line), "data": linedata}
def __init__(self, points, line, patch): if isinstance(points, mpl.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "drag", "idpts": utils.get_id(points, suffix), "idline": utils.get_id(line), "idpatch": utils.get_id(patch)}
def __init__(self, legend, lines, samples): self.lines = lines self.legend = legend self.dict_ = { "type": "linehighlight", "legend_ids": [utils.get_id(line) for line in legend], "line_ids": [utils.get_id(line) for line in lines], "alpha_bg": lines[0].get_alpha(), "alpha_fg": 1.0, }
def __init__(self, _Scatter, _Bar, _DataVariablesList): #Check if isinstance(_Scatter, matplotlib.lines.Line2D): SuffixVariable = "pts" else: SuffixVariable = None #dict self.dict_ = { "type": "linkedview", "idpts": utils.get_id(_Scatter,SuffixVariable), "idline": utils.get_id(_Bar), "data": _DataVariablesList }
def __init__(self, points): if isinstance(points, mpl.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "drag", "id": utils.get_id(points, suffix)}
def __init__(self, plot_elements, labels, ax=None, alpha_unsel=0.2, alpha_over=1., start_visible=True, raw_data=[], option_data=[], limits=None): self.ax = ax if ax: ax = get_id(ax) # start_visible could be a list if isinstance(start_visible, bool): start_visible = [start_visible] * len(labels) elif not len(start_visible) == len(labels): raise ValueError("{} out of {} visible params has been set".format( len(start_visible), len(labels))) mpld3_element_ids = self._determine_mpld3ids(plot_elements) self.mpld3_element_ids = mpld3_element_ids self.dict_ = { "type": "interactive_legend", "element_ids": mpld3_element_ids, "labels": labels, "ax": ax, "option_data": zip(range(len(labels)), labels), "raw_data": raw_data.T, "limits": limits }
def __init__(self, plot_elements, labels, ax=None, title='texte titre', alpha_unsel=0.2, alpha_over=1., start_visible=True, font_size=10, legend_offset=(0,0)): self.ax = ax if ax: ax = get_id(ax) # start_visible could be a list if isinstance(start_visible, bool): start_visible = [start_visible] * len(labels) elif not len(start_visible) == len(labels): raise ValueError("{} out of {} visible params has been set" .format(len(start_visible), len(labels))) mpld3_element_ids = self._determine_mpld3ids(plot_elements) self.mpld3_element_ids = mpld3_element_ids self.dict_ = {"type": "interactive_legend", "title" : title, "element_ids": mpld3_element_ids, "labels": labels, "ax": ax, "alpha_unsel": alpha_unsel, "alpha_over": alpha_over, "start_visible": start_visible, "font_size": font_size, "legend_offset": legend_offset}
def __init__(self, plot_elements, labels, ax=None, alpha_unsel=0.2, alpha_over=1., start_visible=True, default_data=0): self.ax = ax if ax: ax = get_id(ax) # start_visible could be a list if isinstance(start_visible, bool): start_visible = [start_visible] * len(labels) elif not len(start_visible) == len(labels): raise ValueError("{} out of {} visible params has been set".format( len(start_visible), len(labels))) mpld3_element_ids = self._determine_mpld3ids(plot_elements) self.mpld3_element_ids = mpld3_element_ids self.dict_ = { "type": "interactive_legend", "element_ids": mpld3_element_ids, "labels": labels, "ax": ax, "alpha_unsel": alpha_unsel, "alpha_over": alpha_over, "start_visible": [i == default_data for i in range(len(labels))], "active_start": default_data }
def __init__(self, points, histlabel, histline, meanline, histdata, meandata, order): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = { "type": "linkedview", "idpts": utils.get_id(points, suffix), "idlab": utils.get_id(histlabel), "idline": utils.get_id(histline), "idmean": utils.get_id(meanline), "histdata": histdata, "meandata": meandata, "order": list(order.keys()), "labels": list(order.values()), }
def __init__(self, lines, labels, css): self.css_ = css or "" self.lines = lines self.dict_ = {"type": "interactive_legend", "line_ids": [utils.get_id(line) for line in lines], "labels": labels}
def __init__(self, lines): self.lines = lines self.dict_ = { "type": "linehighlight", "line_ids": [utils.get_id(line) for line in lines], "alpha_bg": 1.0, # How light to make highlighted line (can also set to alpha of original mpl plot this way) "alpha_fg": 0.15, } # How dark to make non-highlighted line
def __init__(self, lines): self.lines = lines self.dict_ = { "type": "linehighlight", "line_ids": [utils.get_id(line) for line in lines], "alpha_bg": lines[0].get_alpha(), "alpha_fg": 1.0 }
def __init__(self, points, labels): self.points = points self.labels = labels """if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None""" self.dict_ = {"type": "clickinfo2","id": utils.get_id(points, "pts"),"labels": labels}
def __init__(self, points): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "linkedbrush", "clear_toolbar": False, "id": utils.get_id(points, suffix)}
def __init__(self, points): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "linkedbrush", "clear_toolbar": False, "id": utils.get_id(points, suffix), "buttons": "brush"}
def __init__(self, points, galaxyids, classinfo): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "loadgalaxy", "idpts": utils.get_id(points, suffix), "galaxyids": galaxyids, "classinfo": classinfo}
def __init__(self, points, button=True, enabled=True): if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "linkedbrush", "button": button, "enabled": enabled, "id": get_id(points, suffix)}
def __init__(self, points, urls): self.points = points self.urls = urls if isinstance(points, mpl.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "clickinfo", "id": utils.get_id(points, suffix), "urls": urls}
def __init__(self, bar, labels=None, location="mouse"): import matplotlib from mpld3.utils import get_id if location not in ["bottom left", "top left", "bottom right", "top right", "mouse"]: raise ValueError("invalid location: {0}".format(location)) self.dict_ = {"type": "barlabeltoolTip", "id": get_id(bar), "labels": labels, "location": location}
def get_line_ids(lines: List[mpl_lines.Line2D]) -> List[str]: """Return a list of mpld3 element ids corresponding to the given list of lines. Parameters ---------- lines: List[mpl_lines.Line2D] List of matplotlib lines, generated using `ax.plot(...)`, `Line2D(...)` or equivalent. """ line_ids: List[str] = [] # because lines are built slightly differently depending on how they are defined, # the exact type of the line must be checked before its id extracted for entry in lines: if isinstance(entry, collections.Iterable): line_ids += [get_id(line) for line in entry] else: line_ids.append(get_id(entry)) return line_ids
def __init__(self, points, label=None, hoffset=0, voffset=10, location="mouse"): if location not in ["bottom left", "top left", "bottom right", "top right", "mouse"]: raise ValueError("invalid location: {0}".format(location)) self.dict_ = {"type": "tooltip", "id": get_id(points), "labels": label if label is None else [label], "hoffset": hoffset, "voffset": voffset, "location": location}
def __init__(self, points, labels): self.points = points self.labels = labels """if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None""" self.dict_ = { "type": "clickinfo2", "id": utils.get_id(points, "pts"), "labels": labels }
def __init__(self, line, label=None, hoffset=0, voffset=10, css=None): self.line = line self.label = label self.voffset = voffset self.hoffset = hoffset self.css_ = css or "" self.dict_ = {"type": "linehtmltooltip", "id": get_id(line), "label": label, "hoffset": hoffset, "voffset": voffset}
def __init__(self, points, labels=None, hoffset=0, voffset=10, location="mouse"): if location not in ["bottom left", "top left", "bottom right", "top right", "mouse"]: raise ValueError("invalid location: {0}".format(location)) if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "tooltip", "id": get_id(points, suffix), "labels": labels, "hoffset": hoffset, "voffset": voffset, "location": location}
def __init__(self, points, labels=None, hoffset=0, voffset=10, css=None): self.points = points self.labels = labels self.voffset = voffset self.hoffset = hoffset self.css_ = css or "" if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "htmltooltip", "id": get_id(points, suffix), "labels": labels, "hoffset": hoffset, "voffset": voffset}
def __init__(self, plot_elements, labels, ax=None, alpha_sel=1, alpha_unsel=0.2): self.ax = ax if ax: ax = get_id(ax) mpld3_element_ids = self._determine_mpld3ids(plot_elements) self.mpld3_element_ids = mpld3_element_ids self.dict_ = {"type": "interactive_legend", "element_ids": mpld3_element_ids, "labels": labels, "ax": ax, "alpha_sel": alpha_sel, "alpha_unsel": alpha_unsel}
def __init__(self, points, labels=None, hoffset=0, voffset=10, css=None): self.points = points self.labels = labels self.voffset = voffset self.hoffset = hoffset self.css_ = css or "" if isinstance(points, matplotlib.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "htmltooltip", "id": utils.get_id(points, suffix), "labels": labels, "hoffset": hoffset, "voffset": voffset}
def __init__(self, points, names=None, ncols=3, titles=None, **images): self.dict_ = {"type": "image@point", "id": utils.get_id(points), "images": images, "settings": {}} self.ncols = ncols self.names = names self.npoints = len(next(images.itervalues())) if self.names is None:# pragma: no cover self.names = ["Point {}".format(i) for i in range(self.npoints)] self.dict_["settings"]["names"] = self.names self.titles = titles if self.titles is None:# pragma: no cover self.titles = {k: k for k in images} self.dict_["settings"]["titles"] = self.titles for attr in self.settings: self.dict_["settings"][attr] = getattr(self, attr)
def __init__(self, plot_elements, labels, ax=None, alpha_sel=1, alpha_unsel=0.2): self.ax = ax if ax: ax = get_id(ax) mpld3_element_ids = self._determine_mpld3ids(plot_elements) self.mpld3_element_ids = mpld3_element_ids self.dict_ = { "type": "interactive_legend", "element_ids": mpld3_element_ids, "labels": labels, "ax": ax, "alpha_sel": alpha_sel, "alpha_unsel": alpha_unsel }
def fig_to_html(fig, d3_url=None, mpld3_url=None, no_extras=False, template_type="general", figid=None, use_http=False, **kwargs): template = TEMPLATE_DICT[template_type] d3_url = d3_url or urls.D3_URL mpld3_url = mpld3_url or urls.MPLD3_URL if use_http: d3_url = d3_url.replace('https://', 'http://') mpld3_url = mpld3_url.replace('https://', 'http://') if figid is None: figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10)) elif re.search('\s', figid): raise ValueError("figid must not contain spaces") renderer = MPLD3Renderer() Exporter(renderer, close_mpl=False, **kwargs).run(fig) fig, figure_json, extra_css, extra_js = renderer.finished_figures[0] if no_extras: extra_css = "" extra_js = "" return template.render(figid=json.dumps(figid), d3_url=d3_url, mpld3_url=mpld3_url, figure_json=json.dumps(figure_json, cls=NumpyEncoder), extra_css=extra_css, extra_js=extra_js)
def crop(ax): try: from IPython.html import widgets from IPython.display import display, Javascript from IPython.utils.traitlets import Unicode, Integer except ImportError: raise ImportError("You need IPython 2.0+ to use this feature.") try: import mpld3 from mpld3._display import NumpyEncoder from mpld3.urls import MPLD3_URL, D3_URL from mpld3.utils import get_id from mpld3.mplexporter import Exporter from mpld3.mpld3renderer import MPLD3Renderer except ImportError: raise ImportError("You need mpld3 v0.3 to use this feature.") fig = None if isinstance(ax, mpl.figure.Figure): fig = ax ax = fig.axes[0] xmin, xmax = ax.get_xlim() ymin, ymax = ax.get_ylim() Path = mpath.Path path_data = [ (Path.MOVETO, (xmin + 0.25*(xmax - xmin), ymin + 0.25*(ymax - ymin))), (Path.LINETO, (xmin + 0.25*(xmax - xmin), ymin + 0.75*(ymax - ymin))), (Path.LINETO, (xmin + 0.75*(xmax - xmin), ymin + 0.75*(ymax - ymin))), (Path.LINETO, (xmin + 0.75*(xmax - xmin), ymin + 0.25*(ymax - ymin))), (Path.CLOSEPOLY, (xmin + 0.75*(xmax - xmin), ymin + 0.25*(ymax - ymin))), ] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) fig = ax.figure # plot control points and connecting lines x, y = zip(*path.vertices[:-1]) points = ax.plot(x, y, 'go', ms=10) line = ax.plot(x, y, '-k') ax.set_title("Drag Points to Change Path", fontsize=18) mpld3.plugins.connect(ax.figure, LinkedDragPlugin(points[0], line[0], patch)) renderer = MPLD3Renderer() Exporter(renderer, close_mpl=False).run(fig) fig, figure_json, extra_css, extra_js = renderer.finished_figures[0] my_widget = FigureWidget() my_widget.figure_json = json.dumps(figure_json, cls=NumpyEncoder) my_widget.extra_js = extra_js my_widget.extra_css = extra_css my_widget.figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10)) my_widget.idpts = mpld3.utils.get_id(points[0], 'pts') my_widget.x1 = xmin + 0.25*(xmax - xmin) my_widget.x2 = xmin + 0.25*(xmax - xmin) my_widget.x3 = xmin + 0.75*(xmax - xmin) my_widget.x4 = xmin + 0.75*(xmax - xmin) my_widget.y1 = ymin + 0.25*(ymax - ymin) my_widget.y2 = ymin + 0.75*(ymax - ymin) my_widget.y3 = ymin + 0.75*(ymax - ymin) my_widget.y4 = ymin + 0.75*(ymax - ymin) # Copy over preservation of axis information if looking at a FlowML # generated figure. if hasattr(fig, '_flowml_axis'): my_widget._flowml_axis = fig._flowml_axis display(Javascript(JAVASCRIPT)) fig.clf() return my_widget
def __init__(self, path, type_info, points): with open(path, "r") as js: self.JAVASCRIPT = '\t'.join(js.readlines()) self.dict_ = {"type": type_info, "id": utils.get_id(points)}
def __init__(self, element,info): self.dict_ = {"type": "elementInfo", "id": utils.get_id(element), "info":info}
def __init__(self, points, midpoint, linesla, lineslb, linesra, linesrb, qlmarker, qmmarker, qrmarker, qone, qtwo, rl0, rl1, rr0, rr1): if isinstance(points, mpl.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "drag", "id": utils.get_id(points, suffix), "idmpoint": utils.get_id(midpoint,suffix), "idlinesla": utils.get_id(linesla), "idlineslb": utils.get_id(lineslb), "idlinesra": utils.get_id(linesra), "idlinesrb": utils.get_id(linesrb), "idqlm": utils.get_id(qlmarker,suffix), "idqmm": utils.get_id(qmmarker,suffix), "idqrm": utils.get_id(qrmarker,suffix), "idqone": utils.get_id(qone), "idqtwo": utils.get_id(qtwo), "idrl0": rl0, "idrl1": rl1, "idrr0": rr0, "idrr1": rr1}
def __init__(self, points): self.dict_ = {"type": "clickinfo", "id": utils.get_id(points)}
def __init__(self, element, info): self.dict_ = { "type": "elementInfo", "id": utils.get_id(element), "info": info }
def __init__(self, points, midpoint, g, iters, iter_charac, time, hmax, offm, hugol, hugor, intcl, intcr, hugol2, hugor2, intcl2, intcr2, qlmarker, qmmarker ,qrmarker, shock1, shock2, rar1, rar2, rar1a,rar2a,rar1b,rar2b, rar1c,rar2c,rar1d,rar2d, timedot, timeline, q1, q2): if isinstance(points, mpl.lines.Line2D): suffix = "pts" else: suffix = None self.dict_ = {"type": "drag", "id": utils.get_id(points, suffix), "idmpoint": utils.get_id(midpoint,suffix), "idg" : g, "iditer" : iters, "iditer_charac" : iter_charac, "idtime" : time, "idhmax" : hmax, "idoffm": offm, "idhugol" : utils.get_id(hugol), "idhugor" : utils.get_id(hugor), "idintcl" : utils.get_id(intcl), "idintcr" : utils.get_id(intcr), "idhugol2" : utils.get_id(hugol2), "idhugor2" : utils.get_id(hugor2), "idintcl2" : utils.get_id(intcl2), "idintcr2" : utils.get_id(intcr2), "idqlm": utils.get_id(qlmarker,suffix), "idqmm": utils.get_id(qmmarker,suffix), "idqrm": utils.get_id(qrmarker,suffix), "idshock1" : utils.get_id(shock1), "idshock2" : utils.get_id(shock2), "idrar1" : utils.get_id(rar1), "idrar2" : utils.get_id(rar2), "idrar1a" : utils.get_id(rar1a), "idrar2a" : utils.get_id(rar2a), "idrar1b" : utils.get_id(rar1b), "idrar2b" : utils.get_id(rar2b), "idrar1c" : utils.get_id(rar1c), "idrar2c" : utils.get_id(rar2c), "idrar1d" : utils.get_id(rar1d), "idrar2d" : utils.get_id(rar2d), "idtimedot" : utils.get_id(timedot,suffix), "idtimeline" : utils.get_id(timeline), "idq1" : utils.get_id(q1), "idq2" : utils.get_id(q2) }
def __init__(self, points, labels): self.points = points self.labels = labels self.dict_ = {"type": "clickinfo","id": utils.get_id(points),"labels": labels}
#MAKE LABELS FOR PLOTTED VALUES daily_bar_labels = [] cum_bar_labels = [] for i in range(len(daily_confirmed)): daily_bar_labels.append(datetime_list[i].strftime('%m-%d-%Y') + ": " + str(daily_confirmed[i])) cum_bar_labels.append(datetime_list[i].strftime('%m-%d-%Y') + ": " + str(confirmed_data[i])) last_14_bar_labels = [] for i in range(len(last_14_days)): last_14_bar_labels.append(last_14_days_datetimes[i].strftime('%m-%d-%Y') + ": " + str(last_14_days[i])) mpld3.plugins.connect(fig, mplm.MousePositionDatePlugin()) mpld3.plugins.connect( fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in barpoints], daily_bar_labels)) mpld3.plugins.connect( fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in trend_barpoints], last_14_bar_labels)) mpld3.plugins.connect( fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in cum_barpoints], cum_bar_labels)) mpld3.save_html(fig, "uploads/core/templates/core/plotmiamidade.html") #mpld3.show()
def crop(image): try: from IPython.html import widgets from IPython.display import display, Javascript from IPython.utils.traitlets import Unicode, Integer except ImportError: raise ImportError("You need IPython 2.0+ to use this feature.") try: import mpld3 from mpld3._display import NumpyEncoder from mpld3.urls import MPLD3_URL, D3_URL from mpld3.utils import get_id from mpld3.mplexporter import Exporter from mpld3.mpld3renderer import MPLD3Renderer except ImportError: raise ImportError("You need mpld3 v0.3 to use this feature.") fig, ax = plt.subplots() Path = mpath.Path path_data = [ (Path.MOVETO, (0, 0)), (Path.LINETO, (0, image.shape[0])), (Path.LINETO, (image.shape[1], image.shape[0])), (Path.LINETO, (image.shape[1], 0)), (Path.CLOSEPOLY, (image.shape[1], 0)), ] codes, verts = zip(*path_data) path = mpath.Path(verts, codes) patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5) ax.add_patch(patch) # plot control points and connecting lines x, y = zip(*path.vertices[:-1]) points = ax.plot(x, y, 'go', ms=10) line = ax.plot(x, y, '-k') ax.grid(True, color='gray', alpha=0.5) ax.imshow(image) ax.axis('equal') ax.set_title("Drag Points to Change Path", fontsize=18) mpld3.plugins.connect(fig, LinkedDragPlugin(points[0], line[0], patch)) renderer = MPLD3Renderer() Exporter(renderer, close_mpl=False).run(fig) fig, figure_json, extra_css, extra_js = renderer.finished_figures[0] my_widget = FigureWidget() my_widget.figure_json = json.dumps(figure_json, cls=NumpyEncoder) my_widget.extra_js = extra_js my_widget.extra_css = extra_css my_widget.figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10)) my_widget.idpts = mpld3.utils.get_id(points[0], 'pts') my_widget.y1 = image.shape[0] my_widget.x2 = image.shape[1] my_widget.x2 = image.shape[0] my_widget.x3 = image.shape[1] display(Javascript(JAVASCRIPT)) fig.clf() return my_widget
def plotWithMap(fig,tile_layer = "http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png", withAxes=False,withNonD3Elements=False, **kwargs): d3_url = urls.D3_LOCAL mpld3_url = urls.MPLD3_LOCAL # d3_url, mpld3_url = write_ipynb_local_js() figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10)) renderer = MPLD3Renderer() Exporter(renderer, close_mpl=False).run(fig) fig, figure_json, extra_css, extra_js = renderer.finished_figures[0] extra_css = "" extra_js = "" with open(os.path.join(os.path.dirname(mpld3.__file__), 'js/d3.v3.min.js'),'r') as f: d3_js = f.read() with open(os.path.join(os.path.dirname(mpld3.__file__), 'js/mpld3.v0.2.js'),'r') as f: mpld3_js = f.read() with open(os.path.join(os.path.dirname(__file__), 'pyLeaflet.js'),'r') as f: pyLeaflet_js = f.read() with open(os.path.join(os.path.dirname(__file__), 'draw.js'),'r') as f: draw_js = f.read() with open(os.path.join(os.path.dirname(__file__), 'pyLeaflet.css'),'r') as f: pyLeaflet_css = f.read() if withAxes: withAxesStr="true" else: withAxesStr="false" if withNonD3Elements: withNonD3ElementsStr = "true" else: withNonD3ElementsStr = "false" leaflet_init_js = """ var width = 800, height = 500; var mouseLat = 37; var mouseLng = -90; /******************************************************************************* * * Initialize map layout * *******************************************************************************/ var map = L.map('map').setView([mouseLat, mouseLng],4); //map.scrollWheelZoom.disable(); L.tileLayer('%s', { attribution: '', maxZoom: 18 }).addTo(map); // Use Leaflet to implement a D3 geometric transformation. function projectPoint(x, y) { var point = map.latLngToLayerPoint(new L.LatLng(x, y)); this.stream.point(point.x, point.y); } var transform = d3.geo.transform({point: projectPoint}); var ppath = d3.geo.path().projection(transform); var svg = d3.select(map.getPanes().overlayPane).append('svg').attr('width',5000).attr('height',3000); var g = svg.append('g').attr('class', 'leaflet-zoom-hide').attr('id','%s'); var g2 = svg.append('g').attr('class', 'leaflet-zoom-hide'); """%(tile_layer,figid) # tile_layer = "http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png" # tile_layer = "http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg" kwargs['mpld3_url'] = os.path.dirname(mpld3.__file__)+'/js/mpld3.js' kwargs['d3_url'] = os.path.dirname(mpld3.__file__)+'/js/d3.js' files = {os.path.dirname(mpld3.__file__)+'/js/mpld3.js': ["text/javascript", open(urls.MPLD3_LOCAL, 'r').read()], os.path.dirname(mpld3.__file__)+'/js/d3.js': ["text/javascript", open(urls.D3_LOCAL, 'r').read()]} html = MAP_HTML.render(figid=json.dumps(figid), d3_url=d3_url, mpld3_url=mpld3_url, d3_js=d3_js, mpld3_js=mpld3_js, draw_js=draw_js, figure_json=json.dumps(figure_json), extra_css=extra_css, extra_js=extra_js, pyLeaflet_js=pyLeaflet_js, pyLeaflet_css=pyLeaflet_css, leaflet_init_js=leaflet_init_js, tile_layer=tile_layer, withAxesStr=withAxesStr, withNonD3ElementsStr=withNonD3ElementsStr) serve_and_open(html, ip='localhost', port=8888, n_retries=50, files=files)
def __init__(self, points,labels=None): self.dict_ = {"type": "clickinfo", "id": utils.get_id(points), "labels":labels};
def __init__(self, lines): self.lines = lines self.dict_ = {"type": "linehighlight", "line_ids": [utils.get_id(line) for line in lines], "alpha_bg": 1.0, #How light to make highlighted line (can also set to alpha of original mpl plot this way) "alpha_fg": 0.15} #How dark to make non-highlighted line
def __init__(self, points, urls): self.dict_ = {"type": "clickinfo", "id": utils.get_id(points), "urls": urls }
ax[0].set_title('COVID-19 Cases in Salt Lake County, UT') ax[0].legend() ax[1].legend() #MAKE LABELS FOR PLOTTED VALUES daily_bar_labels = [] cum_bar_labels = [] for i in range(len(daily_confirmed)): daily_bar_labels.append(datetime_list[i].strftime('%m-%d-%Y') + ": " + str(daily_confirmed[i])) cum_bar_labels.append(datetime_list[i].strftime('%m-%d-%Y') + ": " + str(confirmed_data[i])) last_14_bar_labels = [] for i in range(len(last_14_days)): last_14_bar_labels.append(last_14_days_datetimes[i].strftime('%m-%d-%Y') + ": " + str(last_14_days[i])) mpld3.plugins.connect(fig, mplm.MousePositionDatePlugin()) mpld3.plugins.connect(fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in barpoints], daily_bar_labels)) mpld3.plugins.connect(fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in trend_barpoints], last_14_bar_labels)) mpld3.plugins.connect(fig, mplm.BarLabelToolTip([utils.get_id(bar) for bar in cum_barpoints], cum_bar_labels)) mpld3.save_html(fig, "uploads/core/templates/core/plotsalt_lake.html") #mpld3.show()
def plotWithMap(fig,tile_layer = "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",mapWidth=1040,mapHeight=800,saveAs=None, **kwargs): figid = 'fig_' + get_id(fig) + str(int(random.random() * 1E10)) renderer = MPLD3Renderer() Exporter(renderer, close_mpl=True).run(fig) fig, figure_json, extra_css, extra_js = renderer.finished_figures[0] extra_css = "" extra_js = "" # print json.dumps(figure_json) leaflet_init_js = """ var width = 1040, height = 640; var mouseLat = 37; var mouseLng = -90; /******************************************************************************* * * Initialize map layout * *******************************************************************************/ var map = L.map('map').setView([mouseLat, mouseLng],4); //map.scrollWheelZoom.disable(); L.tileLayer('%s', { attribution: '', maxZoom: 18 }).addTo(map); // Use Leaflet to implement a D3 geometric transformation. function projectPoint(x, y) { var point = map.latLngToLayerPoint(new L.LatLng(x, y)); this.stream.point(point.x, point.y); } var transform = d3.geo.transform({point: projectPoint}); var ppath = d3.geo.path().projection(transform); var background = d3.select(map.getPanes().overlayPane) .insert("svg") .attr('width',width+1500+'px') .attr('height',height+1500+'px') background.append('rect') .attr('width',width+1500+'px') .attr('height',height+1500+'px') .style('fill','white') .style('fill-opacity',.4) var svg = d3.select(map.getPanes().overlayPane).append('svg').attr('width',5000).attr('height',3000); var g2 = svg.append('g').attr('class', 'leaflet-zoom-hide'); """%(tile_layer) # tile_layer = "http://{s}.www.toolserver.org/tiles/bw-mapnik/{z}/{x}/{y}.png" # tile_layer = "http://{s}.tile.stamen.com/terrain/{z}/{x}/{y}.jpg" # tile_layer = "http://{s}.tile.stamen.com/toner/{z}/{x}/{y}.jpg" datafile = tempfile.NamedTemporaryFile(delete=False) datafile.write('mdata = '+json.dumps(figure_json)) datafile.close() if saveAs is None: kwargs['mpld3_url'] = '/mpld3.js' kwargs['mpld3_css_url'] = '/mpld3.css' kwargs['d3_url'] = '/d3.js' kwargs['leaflet_js_url'] = '/leaflet.js' kwargs['leaflet_css_url'] = '/leaflet.css' files = {'/mpld3.js': ["text/javascript", open(mpld3.urls.MPLD3MIN_LOCAL, 'r').read()], '/d3.js': ["text/javascript", open(mpld3.urls.D3_LOCAL, 'r').read()], '/leaflet.js': ["text/javascript", open(os.path.join(os.path.dirname(__file__), 'js/leaflet.js'),'r').read()], '/leaflet.css': ["text/css", open(os.path.join(os.path.dirname(__file__), 'css/leaflet.css'),'r').read()], '/mpld3.css': ["text/css", open(os.path.join(os.path.dirname(__file__), 'css/mpld3.css'),'r').read()], '/images/layers-2x.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/layers-2x.png'),'r').read()], '/images/layers.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/layers.png'),'r').read()], '/images/marker-icon-2x.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-icon-2x.png'),'r').read()], '/images/marker-icon.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-icon.png'),'r').read()], '/images/marker-shadow.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-shadow.png'),'r').read()], '/favicon.ico': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/favicon.ico'),'r').read()], '/data.js': ["text/javascript", open(datafile.name,'r').read()]} else: kwargs['mpld3_url'] = 'http://mpld3.github.io/js/mpld3.v0.2.js' kwargs['mpld3_css_url'] = 'http://mpld3.github.io/_static/mpld3.css' kwargs['d3_url'] = 'https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.16/d3.min.js' kwargs['leaflet_js_url'] = "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.js" kwargs['leaflet_css_url'] = "https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css" files = { '/images/layers-2x.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/layers-2x.png'),'r').read()], '/images/layers.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/layers.png'),'r').read()], '/images/marker-icon-2x.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-icon-2x.png'),'r').read()], '/images/marker-icon.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-icon.png'),'r').read()], '/images/marker-shadow.png': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/marker-shadow.png'),'r').read()], '/favicon.ico': ["text/css", open(os.path.join(os.path.dirname(__file__), 'images/favicon.ico'),'r').read()], '/data.js': ["text/javascript", open(datafile.name,'r').read()]} html = MAP_HTML.render(figid=json.dumps(figid), mapWidth = mapWidth, mapHeight=mapHeight, d3_url=kwargs['d3_url'], mpld3_url=kwargs['mpld3_url'], draw_js_content=open(os.path.join(os.path.dirname(__file__), 'js/draw.js'),'r').read(), data_content=open(datafile.name,'r').read(), leaflet_js_url=kwargs['leaflet_js_url'], leaflet_css_url=kwargs['leaflet_css_url'], mpld3_css_url=kwargs['mpld3_css_url'], extra_css=extra_css, extra_js=extra_js, pyLeaflet_css_content=open(os.path.join(os.path.dirname(__file__), 'css/pyLeaflet.css'),'r').read(), leaflet_init_js=leaflet_init_js, tile_layer=tile_layer) if saveAs is not None: with open(saveAs, "w") as text_file: text_file.write(html) serve_and_open(html, ip='localhost', port=8080, n_retries=50, files=files) os.unlink(datafile.name) return html