我们从Python开源项目中,提取了以下13个代码示例,用于说明如何使用IPython.display.SVG。
def display_graph(g, format='svg', include_asset_exists=False): """ Display a TermGraph interactively from within IPython. """ try: import IPython.display as display except ImportError: raise NoIPython("IPython is not installed. Can't display graph.") if format == 'svg': display_cls = display.SVG elif format in ("jpeg", "png"): display_cls = partial(display.Image, format=format, embed=True) out = BytesIO() _render(g, out, format, include_asset_exists=include_asset_exists) return display_cls(data=out.getvalue())
def _get_display_cls(format): """ Get the appropriate IPython display class for `format`. Returns `IPython.display.SVG` if format=='svg', otherwise `IPython.display.Image`. If IPython is not importable, return dummy function that swallows its arguments and returns None. """ dummy = lambda *args, **kwargs: None try: import IPython.display as display except ImportError: # Can't return a display object if no IPython. return dummy if format in IPYTHON_NO_DISPLAY_FORMATS: # IPython can't display this format natively, so just return None. return dummy elif format in IPYTHON_IMAGE_FORMATS: # Partially apply `format` so that `Image` and `SVG` supply a uniform # interface to the caller. return partial(display.Image, format=format) elif format == 'svg': return display.SVG else: raise ValueError("Unknown format '%s' passed to `dot_graph`" % format)
def svg(self): from IPython.display import SVG return SVG(self._repr_svg_())
def ishow(cls, figure_or_data, format='png', width=None, height=None, scale=None): """Display a static image of the plot described by `figure_or_data` in an IPython Notebook. positional arguments: - figure_or_data: The figure dict-like or data list-like object that describes a plotly figure. Same argument used in `py.plot`, `py.iplot`, see https://plot.ly/python for examples - format: 'png', 'svg', 'jpeg', 'pdf' - width: output width - height: output height - scale: Increase the resolution of the image by `scale` amount Only valid for PNG and JPEG images. example:
import plotly.plotly as py fig = {'data': [{'x': [1, 2, 3], 'y': [3, 1, 5], 'type': 'bar'}]} py.image.ishow(fig, 'png', scale=3) """ if format == 'pdf': raise exceptions.PlotlyError( "Aw, snap! " "It's not currently possible to embed a pdf into " "an IPython notebook. You can save the pdf " "with the `image.save_as` or you can " "embed an png, jpeg, or svg.") img = cls.get(figure_or_data, format, width, height, scale) from IPython.display import display, Image, SVG if format == 'svg': display(SVG(img)) else: display(Image(img))
```
def plotPipelineStructure(self): ''' Plot pipeline structure @return iPython display object ''' #Graph setup g1 = gv.Digraph(format='svg') g1.graph_attr['rankdir'] = 'LR' g1.node_attr['shape'] = 'rounded' g1.node_attr['fontname'] = 'Arial' g1.node_attr['fontsize'] = '9' g1.node_attr['style'] = 'filled' g1.node_attr['margin'] = '0.1' g1.node_attr['height'] = '0.1' g1.node_attr['fillcolor'] = '#fff7da' #g1.node_attr['shape'] = 'plaintext' #use this to remove boxes around nodes nodelist= self.getMetadataNestedGraph() print (nodelist) src = Source(nodelist) print (dir(src)) src.format='svg' src.render('img/plotPipelineStructure') # for s in nodelist: # g1.node(s) # g1.edges(zip(nodelist, nodelist[1:])) # g1.render('img/plotPipelineStructure') # print(nodelist) # print(g1.source) # return display(SVG('img/plotPipelineStructure.svg')) return display(SVG('img/plotPipelineStructure.svg')) #++++++++++ NEW Victor +++++++++++
def draw_strokes( data, factor = 10, svg_filename = 'sample.svg' ): min_x, max_x, min_y, max_y = get_bounds( data, factor ) dims = ( 50 + max_x - min_x, 50 + max_y - min_y ) dwg = svgwrite.Drawing( svg_filename, size = dims ) dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) ) lift_pen = 1 abs_x = 25 - min_x abs_y = 25 - min_y p = "M%s, %s " % ( abs_x, abs_y ) command = "m" for i in range( len( data ) ): if ( lift_pen == 1 ): command = "m" elif ( command != "l" ): command = "l" else: command = "" x = float( data[ i, 0 ] )/factor y = float( data[ i, 1 ] )/factor lift_pen = data[ i, 2 ] p += command+str( x )+", "+str( y )+" " the_color = "black" stroke_width = 1 dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( "none" ) ) dwg.save( ) display( SVG( dwg.tostring( ) ) )
def draw_strokes_custom_color( data, factor = 10, svg_filename = 'test.svg', color_data = None, stroke_width = 1 ): min_x, max_x, min_y, max_y = get_bounds( data, factor ) dims = ( 50 + max_x - min_x, 50 + max_y - min_y ) dwg = svgwrite.Drawing( svg_filename, size = dims ) dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) ) lift_pen = 1 abs_x = 25 - min_x abs_y = 25 - min_y for i in range( len( data ) ): x = float( data[ i, 0 ] )/factor y = float( data[ i, 1 ] )/factor prev_x = abs_x prev_y = abs_y abs_x += x abs_y += y if ( lift_pen == 1 ): p = "M "+str( abs_x )+", "+str( abs_y )+" " else: p = "M +"+str( prev_x )+", "+str( prev_y )+" L "+str( abs_x )+", "+str( abs_y )+" " lift_pen = data[ i, 2 ] the_color = "black" if ( color_data is not None ): the_color = "rgb( "+str( int( color_data[ i, 0 ] ) )+", "+str( int( color_data[ i, 1 ] ) )+", "+str( int( color_data[ i, 2 ] ) )+" )" dwg.add( dwg.path( p ).stroke( the_color, stroke_width ).fill( the_color ) ) dwg.save( ) display( SVG( dwg.tostring( ) ) )
def draw_strokes_pdf( data, param, factor = 10, svg_filename = 'sample_pdf.svg' ): min_x, max_x, min_y, max_y = get_bounds( data, factor ) dims = ( 50 + max_x - min_x, 50 + max_y - min_y ) dwg = svgwrite.Drawing( svg_filename, size = dims ) dwg.add( dwg.rect( insert = ( 0, 0 ), size = dims, fill = 'white' ) ) abs_x = 25 - min_x abs_y = 25 - min_y num_mixture = len( param[ 0 ][ 0 ] ) for i in range( len( data ) ): x = float( data[ i, 0 ] )/factor y = float( data[ i, 1 ] )/factor for k in range( num_mixture ): pi = param[ i ][ 0 ][ k ] if pi > 0.01: # optimisation, ignore pi's less than 1% chance mu1 = param[ i ][ 1 ][ k ] mu2 = param[ i ][ 2 ][ k ] s1 = param[ i ][ 3 ][ k ] s2 = param[ i ][ 4 ][ k ] sigma = np.sqrt( s1*s2 ) dwg.add( dwg.circle( center = ( abs_x+mu1*factor, abs_y+mu2*factor ), r = int( sigma*factor ) ).fill( 'red', opacity = pi/( sigma*sigma*factor ) ) ) prev_x = abs_x prev_y = abs_y abs_x += x abs_y += y dwg.save( ) display( SVG( dwg.tostring( ) ) )
def get_svg(self): """ ???????????????SVG??? """ dr=sw.Drawing("hoge.svg",(150,150)) c=(75,75) dr.add(dr.line(c,(c[0]+50*np.sin(self.th),c[1]+50*np.cos(self.th)), stroke=sw.utils.rgb(0,0,0),stroke_width=3)) return SVG(dr.tostring()) # ?????????????????????????????? # ?????????????????????????????????
def display(self, *args): """Display interactive graph""" if self._display_stack: if not self.delayed: self._display_stack -= 1 if self._display_stack: # Skip display if other widgets will invoke display soon return False self.output_widget.clear_output() with self.output_widget: work_list, references = self.graph() display(self._svg_name) svg = SVG(self._svg_name) svg._data = svg._data[:4] + ' class="refgraph"' + svg._data[4:] display(svg) interaction = """ $(".hoverable polyline, .hoverable line").mouseenter( function(e) { //e.stopPropagation(); $(this).css("stroke", "blue"); $(this).css("stroke-width", "3px"); }).mouseleave( function() { $(this).css("stroke", "black"); $(this).css("stroke-width", "inherit"); }); """ display(Javascript(interaction)) display(HTML(""" <script type="text/javascript"> %s require(["./svg-pan-zoom"], function(svgPanZoom) { svgPanZoom('.refgraph', {'minZoom': 0.1}); }); </script> """ % ( open( Path(__file__) / ".." / ".." / "resources" / "svg-pan-zoom.min.js" ).read(), ))) return True
def plotPipelineInstance(self): ''' Plot current instance of pipeline stages with metadata @return iPython display object ''' #Graph setup g1 = gv.Digraph(format='svg') g1.graph_attr['rankdir'] = 'LR' g1.node_attr['shape'] = 'rounded' g1.node_attr['fontname'] = 'Arial' g1.node_attr['fontsize'] = '9' g1.node_attr['style'] = 'filled' g1.node_attr['margin'] = '0.1' g1.node_attr['height'] = '0.1' g1.node_attr['fillcolor'] = '#d8e9fd' #g1.node_attr['shape'] = 'plaintext' #use this to remove boxes around nodes # Some stagecontainers directly return the metadata as string, # others return a list of strings for each item in the stage # container. metadata_list = [] for s in self.stage_containers: first_metadata = s.getMetadata() if isinstance(first_metadata, str): metadata_list.append(first_metadata) else: for second_metadata in first_metadata: metadata_list.append(second_metadata) nodelist = [re.sub('\:',';', metadata) for metadata in metadata_list] for s in nodelist: g1.node(s) g1.edges(zip(nodelist, nodelist[1:])) g1.render('img/plotPipelineInstance') #print(g1.source) #return display(Image('img/pipelinePlot.svg')) return display(SVG('img/plotPipelineInstance.svg'))
def drawSVGsToHTMLGrid(svgs, cssTableName='default', tableHeader='', namesSVGs=[], size=(150,150), numColumns=4, numRowsShown=2, noHeader=False): rows=[] names=copy.deepcopy(namesSVGs) rows = [SVG(i).data for i in svgs] d=int(len(rows)/numColumns) x=len(rows)%numColumns if x > 0: rows+=['']*(numColumns-x) d+=1 if len(names)>0: names+=['']*(numColumns-x) rows=np.array(rows).reshape(d,numColumns) finalRows=[] if len(names)>0: names = np.array(names).reshape(d,numColumns) for r,n in zip(rows,names): finalRows.append(r) finalRows.append(n) d*=2 else: finalRows=rows headerRemove = int(max(numColumns,d)) df=pd.DataFrame(finalRows) style = '<style>\n' style += 'table.'+cssTableName+' { border-collapse: collapse; border: none;}\n' style += 'table.'+cssTableName+' tr, table.'+cssTableName+' th, table.'+cssTableName+' td { border: none;}\n' style += 'table.'+cssTableName+' td { width: '+str(size[0])+'px; max-height: '+str(size[1])+'px; background-color: white; text-align:center;}\n' if noHeader: style += 'table.'+cssTableName+' th { width: '+str(size[0])+'px; max-height: 0px; background-color: white;}\n' else: style += 'table.'+cssTableName+' th { color: #ffffff; background-color: #848482; text-align: center;}\n' style += '.headline { color: #ffffff; background-color: #848482; text-align: center; font-size: 18px;\ font-weight: bold; padding: 10px 10px 10px 10px}\n' style += '</style>\n' if not noHeader: style += '<div class="headline">'+str(tableHeader)+'</div>\n' style += '<div id="" style="overflow-y:scroll; overflow-x:hidden; max-height:'+str(size[1]*numRowsShown+size[1]/2)+'px; background-color: white; border:1px solid grey">\n' dfhtml=style+df.to_html()+'\n</div>\n' dfhtml=dfhtml.replace('class="dataframe"','class="'+cssTableName+'"') dfhtml=dfhtml.replace('<th></th>','') for i in range(0,headerRemove): dfhtml=dfhtml.replace('<th>'+str(i)+'</th>','') return dfhtml # build an svg grid image to print