Save the rendered html to a file and returns an IFrame to display the plot in the notebook.
488779
def plot_and_save(self,
                      data,
                      w=800,
                      h=420,
                      filename='chart',
                      overwrite=True):
        """"""
        self.save(data, filename, overwrite)
        return IFrame(filename + '.html', w, h)
663445
def create_html(self, filename=None):
        """"""
        
        if isinstance(self.style, str):
            style = "'{}'".format(self.style)
        else:
            style = self.style
        
        options = dict(
            gl_js_version=GL_JS_VERSION,
            accessToken=self.access_token,
            div_id=self.div_id,
            style=style,
            center=list(self.center),
            zoom=self.zoom,
            geojson_data=json.dumps(self.data, ensure_ascii=False),
            belowLayer=self.below_layer,
            opacity=self.opacity,
            minzoom=self.min_zoom,
            maxzoom=self.max_zoom,
            pitch=self.pitch, 
            bearing=self.bearing,
            boxZoomOn=json.dumps(self.box_zoom_on),
            doubleClickZoomOn=json.dumps(self.double_click_zoom_on),
            scrollZoomOn=json.dumps(self.scroll_zoom_on),
            touchZoomOn=json.dumps(self.touch_zoom_on),
            popupOpensOnHover=self.popup_open_action=='hover',
            includeSnapshotLinks=self.add_snapshot_links,
            preserveDrawingBuffer=json.dumps(self.add_snapshot_links),
            showScale=self.scale,
            scaleUnits=self.scale_unit_system,
            scaleBorderColor=self.scale_border_color,
            scalePosition=self.scale_position,
            scaleFillColor=self.scale_background_color,
            scaleTextColor=self.scale_text_color,
        )

        if self.legend:

            if all([self.legend, self.legend_gradient, self.legend_function == 'radius']):
                raise LegendError(' '.join(['Gradient legend format not compatible with a variable radius legend.',
                                            'Please either change `legend_gradient` to False or `legend_function` to "color".']))

            options.update(
                showLegend=self.legend,
                legendLayout=self.legend_layout,
                legendFunction=self.legend_function,
                legendStyle=self.legend_style, # reserve for custom CSS
                legendGradient=json.dumps(self.legend_gradient),
                legendFill=self.legend_fill,
                legendHeaderFill=self.legend_header_fill,
                legendTextColor=self.legend_text_color,
                legendNumericPrecision=json.dumps(self.legend_text_numeric_precision),
                legendTitleHaloColor=self.legend_title_halo_color,
                legendKeyShape=self.legend_key_shape,
                legendKeyBordersOn=json.dumps(self.legend_key_borders_on)
            )

        if self.vector_source:
            options.update(
                vectorUrl=self.vector_url,
                vectorLayer=self.vector_layer_name,
                vectorJoinDataProperty=self.vector_join_property,
                joinData=json.dumps(False),
                dataJoinProperty=self.data_join_property,
                enableDataJoin=not self.disable_data_join
            )
            data = geojson_to_dict_list(self.data)
            if bool(data):
                options.update(joinData=json.dumps(data, ensure_ascii=False))

        if self.label_property is None:
            options.update(labelProperty=None)
        else:
            options.update(labelProperty='{' + self.label_property + '}')
        
        options.update(
            labelColor=self.label_color,
            labelSize=self.label_size,
            labelHaloColor=self.label_halo_color,
            labelHaloWidth=self.label_halo_width
        )

        self.add_unique_template_variables(options)

        if filename:
            html = templates.format(self.template, **options)
            with codecs.open(filename, "w", "utf-8-sig") as f:
                f.write(html)
            return None
        else:
            return templates.format(self.template, **options)
831176
def export_html(path="./plot.html", to_png=false)
      path = File.expand_path(path, Dir::pwd)
      body = generate_html("../templates/iruby.erb")
      temp_path = File.expand_path("../templates/static_html.erb", __FILE__)
      template = File.read(temp_path)
      num = File.write(path, ERB.new(template).result(binding))
      "Plot was saved to " + path
    end
1334929
def render
      result = {:text => @generator.to_s, :content_type => Mime::JS}

      # iframed uploads context overloading
      if @template.request.content_type == 'multipart/form-data'
        result[:content_type] = Mime::HTML
        result[:layout]       = nil
        result[:text]         = %Q{
<!-- iframed uploads JS responses layout -->
<html>
  <head>
    <script type="text/javascript">
      with (window.parent) {
        #{result[:text]}
      }
    </script>
  </head>
</html>
        }.strip
      end

      result.merge! @options
    end
126766
def build_html():
    """"""
    source = AjaxDataSource(data_url='./data',
                            polling_interval=INTERVAL,
                            method='GET')

    # OHLC plot
    p = figure(plot_height=400,
               title='OHLC',
               sizing_mode='scale_width',
               tools="xpan,xwheel_zoom,xbox_zoom,reset",
               x_axis_type=None,
               y_axis_location="right",
               y_axis_label="Price ($)")
    p.x_range.follow = "end"
    p.x_range.follow_interval = 100
    p.x_range.range_padding = 0
    p.line(x='time', y='average', alpha=0.25, line_width=3, color='black',
           source=source)
    p.line(x='time', y='ma', alpha=0.8, line_width=2, color='steelblue',
           source=source)
    p.segment(x0='time', y0='low', x1='time', y1='high', line_width=2,
              color='black', source=source)
    p.segment(x0='time', y0='open', x1='time', y1='close', line_width=8,
              color='color', source=source, alpha=0.8)

    # MACD plot
    p2 = figure(plot_height=200,
                title='MACD',
                sizing_mode='scale_width',
                x_range=p.x_range,
                x_axis_label='Time (s)',
                tools="xpan,xwheel_zoom,xbox_zoom,reset",
                y_axis_location="right")
    p2.line(x='time', y='macd', color='darkred', line_width=2, source=source)
    p2.line(x='time', y='macd9', color='navy', line_width=2, source=source)
    p2.segment(x0='time', y0=0, x1='time', y1='macdh', line_width=6, color='steelblue',
               alpha=0.5, source=source)

    # Combine plots together
    plot = gridplot([[p], [p2]], toolbar_location="left", plot_width=1000)

    # Compose html from plots and template
    script, div = components(plot, theme=theme)
    html = template.render(resources=CDN.render(), script=script, div=div)

    return html
907618
def to_html(self, show_mean=None, sortable=None, colorize=True, *args,
                **kwargs):
        """"""
        if show_mean is None:
            show_mean = self.show_mean
        if sortable is None:
            sortable = self.sortable
        df = self.copy()
        if show_mean:
            df.insert(0, 'Mean', None)
            df.loc[:, 'Mean'] = ['%.3f' % self[m].mean() for m in self.models]
        html = df.to_html(*args, **kwargs)  # Pandas method
        html, table_id = self.annotate(df, html, show_mean, colorize)
        if sortable:
            self.dynamify(table_id)
        return html
271310
def middle_frame(obj):
    ""
    plot, renderer, fmt = single_frame_plot(obj)
    middle_frame = int(len(plot) / 2)
    plot.update(middle_frame)
    return {'text/html': renderer.html(plot, fmt)}
1032676
def first_frame(obj):
    ""
    plot, renderer, fmt = single_frame_plot(obj)
    plot.update(0)
    return {'text/html': renderer.html(plot, fmt)}
1093189
def to_html(self):
        
        icon = self.html_icon()
        attributes = self.html_attributes()
        # Deal with long file names that prevent wrapping
        wrappable_text = self.to_text().replace(os.sep, '<wbr>' + os.sep)
        if icon is not '' and attributes is not '':
            return '<span%s>%s%s</span>' % (attributes, icon, wrappable_text)
        else:
            return self.to_text()
639286
def save(
        self,
        filename: Optional[str] = None,
        show_link: bool = True,
        auto_open: bool = False,
        output: str = 'file',
        plotlyjs: bool = True,
    ) -> str:
        """"""
        if filename is None:
            filename = NamedTemporaryFile(prefix='plotly', suffix='.html', delete=False).name
        # NOTE: this doesn't work for output 'div'
        py.plot(
            self,
            show_link=show_link,
            filename=filename,
            auto_open=auto_open,
            output_type=output,
            include_plotlyjs=plotlyjs,
        )
        return filename
703479
def to_html(self, write_to):
        
        page_html = self.get_html()

        with open(write_to, "wb") as writefile:
            writefile.write(page_html.encode("utf-8"))
968540
def __save_plots_of_the_current_page(self, section, page, output_path):
        """"""
        
        for key in self.sections[section].pages[page].elements.keys():
            print(section, page, key) # debug print
            
            buf_temp = self.sections[section].pages[page].elements[key].plot_object
            if buf_temp is not None :

                plot_path = os.path.join(output_path, "output", self.name, "site", section, key + ".svg")
                
                
                try :
                    my_file = open(plot_path, "wb")
                    my_file.write(buf_temp)
                    my_file.close()
                except Exception as e:
                    print (e)
                    print ("In {section} and {page}, an element exists without a valid plot object.".format(section = section, page = page))
820475
def save(self, model, path=''):
        """"""
        path = path.strip('/')

        if 'type' not in model:
            raise web.HTTPError(400, u'No file type provided')
        if 'content' not in model and model['type'] != 'directory':
            raise web.HTTPError(400, u'No file content provided')

        self.run_pre_save_hook(model=model, path=path)

        os_path = self._get_os_path(path)
        self.log.debug("Saving %s", os_path)
        try:
            if model['type'] == 'notebook':

                # NEW
                file_ext = _file_extension(os_path)
                if file_ext == '.ipynb':
                    nb = nbformat.from_dict(model['content'])
                    self.check_and_sign(nb, path)
                    self._save_notebook(os_path, nb)
                else:

                    contents = convert(model['content'],
                                       from_='notebook',
                                       to=self.format)

                    # Save a text file.
                    if (format_manager().file_type(self.format) in
                        ('text', 'json')):
                        self._save_file(os_path, contents, 'text')
                    # Save to a binary file.
                    else:
                        format_manager().save(os_path, contents,
                                              name=self.format,
                                              overwrite=True)

                # One checkpoint should always exist for notebooks.
                if not self.checkpoints.list_checkpoints(path):
                    self.create_checkpoint(path)
            elif model['type'] == 'file':
                # Missing format will be handled internally by _save_file.
                self._save_file(os_path, model['content'], model.get('format'))
            elif model['type'] == 'directory':
                self._save_directory(os_path, model, path)
            else:
                raise web.HTTPError(400, "Unhandled contents type: %s" % model['type'])
        except web.HTTPError:
            raise
        except Exception as e:
            self.log.error(u'Error while saving file: %s %s', path, e, exc_info=True)
            raise web.HTTPError(500, u'Unexpected error while saving file: %s %s' % (path, e))

        validation_message = None
        if model['type'] == 'notebook':
            self.validate_notebook_model(model)
            validation_message = model.get('message', None)

        model = self.get(path, content=False)
        if validation_message:
            model['message'] = validation_message

        self.run_post_save_hook(model=model, os_path=os_path)

        return model
144279
function render() {
		var labels = options.labels,
			credits = options.credits,
			creditsHref;

		// Title
		setTitle();


		// Legend
		legend = chart.legend = new Legend();

		// Get margins by pre-rendering axes
		getMargins();
		each(axes, function (axis) {
			axis.setTickPositions(true); // update to reflect the new margins
		});
		adjustTickAmounts();
		getMargins(); // second pass to check for new labels


		// Draw the borders and backgrounds
		drawChartBox();

		// Axes
		if (hasCartesianSeries) {
			each(axes, function (axis) {
				axis.render();
			});
		}


		// The series
		if (!chart.seriesGroup) {
			chart.seriesGroup = renderer.g('series-group')
				.attr({ zIndex: 3 })
				.add();
		}
		each(series, function (serie) {
			serie.translate();
			serie.setTooltipPoints();
			serie.render();
		});


		// Labels
		if (labels.items) {
			each(labels.items, function () {
				var style = extend(labels.style, this.style),
					x = pInt(style.left) + plotLeft,
					y = pInt(style.top) + plotTop + 12;

				// delete to prevent rewriting in IE
				delete style.left;
				delete style.top;

				renderer.text(
					this.html,
					x,
					y
				)
				.attr({ zIndex: 2 })
				.css(style)
				.add();

			});
		}

		// Toolbar (don't redraw)
		if (!chart.toolbar) {
			chart.toolbar = Toolbar();
		}

		// Credits
		if (credits.enabled && !chart.credits) {
			creditsHref = credits.href;
			chart.credits = renderer.text(
				credits.text,
				0,
				0
			)
			.on('click', function () {
				if (creditsHref) {
					location.href = creditsHref;
				}
			})
			.attr({
				align: credits.position.align,
				zIndex: 8
			})
			.css(credits.style)
			.add()
			.align(credits.position);
		}

		placeTrackerGroup();

		// Set flag
		chart.hasRendered = true;

		// If the chart was rendered outside the top container, put it back in
		if (renderToClone) {
			renderTo.appendChild(container);
			discardElement(renderToClone);
			//updatePosition(container);
		}
	}
408071
def export(path=None, user_content=False, context=None,
           username=None, password=None, render_offline=False,
           render_wide=False, render_inline=True, out_filename=None,
           api_url=None, title=None, quiet=False, grip_class=None):
    
    export_to_stdout = out_filename == '-'
    if out_filename is None:
        if path == '-':
            export_to_stdout = True
        else:
            filetitle, _ = os.path.splitext(
                os.path.relpath(DirectoryReader(path).root_filename))
            out_filename = '{0}.html'.format(filetitle)

    if not export_to_stdout and not quiet:
        print('Exporting to', out_filename, file=sys.stderr)

    page = render_page(path, user_content, context, username, password,
                       render_offline, render_wide, render_inline, api_url,
                       title, None, quiet, grip_class)

    if export_to_stdout:
        try:
            print(page)
        except IOError as ex:
            if ex.errno != 0 and ex.errno != errno.EPIPE:
                raise
    else:
        with io.open(out_filename, 'w', encoding='utf-8') as f:
            f.write(page)
1130878
def plot(self, data, w=800, h=420):
        """"""
        return HTML(
            self.iframe.format(
                source=self.render(
                    data=data, div_id="chart", head=self.head),
                w=w,
                h=h))
965325
def save_to_file(self,
                     file_path,
                     labels=None,
                     predict_proba=True,
                     show_predicted_value=True,
                     **kwargs):
        
        file_ = open(file_path, 'w', encoding='utf8')
        file_.write(self.as_html(labels=labels,
                                 predict_proba=predict_proba,
                                 show_predicted_value=show_predicted_value,
                                 **kwargs))
        file_.close()