Visualizers

As of v2.0, our popular visualizers, displaCy and displaCy ENT are finally an official part of the library. Visualizing a dependency parse or named entities in a text is not only a fun NLP demo – it can also be incredibly helpful in speeding up development and debugging your code and training process. Instead of printing a list of dependency labels or entity spans, you can simply pass your Doc objects to displacy and view the visualizations in your browser, or export them as HTML files or vector graphics.

If you're running a Jupyter notebook, displaCy will detect this and return the markup in a format ready to be rendered and exported.

Getting started

The quickest way visualize Doc is to use displacy.serve . This will spin up a simple web server and let you view the result straight from your browser. displaCy can either take a single Doc or a list of Doc objects as its first argument. This lets you construct them however you like – using any model or modifications you like.

Visualizing the dependency parse

The dependency visualizer, dep, shows part-of-speech tags and syntactic dependencies.

Dependency example

import spacy from spacy import displacy nlp = spacy.load('en') doc = nlp(u'This is a sentence.') displacy.serve(doc, style='dep')

The argument options lets you specify a dictionary of settings to customise the layout, for example:

NameTypeDescriptionDefault
compactbool"Compact mode" with square arrows that takes up less space.False
colorunicodeText color (HEX, RGB or color names).'#000000'
bgunicodeBackground color (HEX, RGB or color names).'#ffffff'
fontunicodeFont name or font family for all text.'Arial'

For a list of all available options, see the displacy API documentation .

Visualizing the entity recognizer

The entity visualizer, ent, highlights named entities and their labels in a text.

Named Entity example

import spacy from spacy import displacy text = """But Google is starting from behind. The company made a late push into hardware, and Apple’s Siri, available on iPhones, and Amazon’s Alexa software, which runs on its Echo and Dot devices, have clear leads in consumer adoption.""" nlp = spacy.load('custom_ner_model') doc = nlp(text) displacy.serve(doc, style='ent')

The entity visualizer lets you customise the following options:

NameTypeDescriptionDefault
entslist Entity types to highlight (None for all types).None
colorsdict Color overrides. Entity types in lowercase should be mapped to color names or values.{}

If you specify a list of ents, only those entity types will be rendered – for example, you can choose to display PERSON entities. Internally, the visualizer knows nothing about available entity types and will render whichever spans and labels it receives. This makes it especially easy to work with custom entity types. By default, displaCy comes with colours for all entity types supported by spaCy. If you're using custom entity types, you can use the colors setting to add your own colours for them.

The above example uses a little trick: Since the background colour values are added as the background style attribute, you can use any valid background value or shorthand — including gradients and even images!

Adding titles to documents

Rendering several large documents on one page can easily become confusing. To add a headline to each visualization, you can add a title to its user_data. User data is never touched or modified by spaCy.

doc = nlp(u'This is a sentence about Google.')
doc.user_data['title'] = 'This is a title'
displacy.serve(doc, style='ent')

This feature is espeically handy if you're using displaCy to compare performance at different stages of a process, e.g. during training. Here you could use the title for a brief description of the text example and the number of iterations.

Rendering visualizations

If you don't need the web server and just want to generate the markup – for example, to export it to a file or serve it in a custom way – you can use displacy.render . It works the same way, but returns a string containing the markup.

Example

import spacy from spacy import displacy nlp = spacy.load('en') doc1 = nlp(u'This is a sentence.') doc2 = nlp(u'This is another sentence.') html = displacy.render([doc1, doc2], style='dep', page=True)

page=True renders the markup wrapped as a full HTML page. For minified and more compact HTML markup, you can set minify=True. If you're rendering a dependency parse, you can also export it as an .svg file.

svg = displacy.render(doc, style='dep')
output_path = Path('/images/sentence.svg')
output_path.open('w', encoding='utf-8').write(svg)

Example: Export SVG graphics of dependency parses

Example

import spacy from spacy import displacy from pathlib import Path nlp = spacy.load('en') sentences = ["This is an example.", "This is another one."] for sent in sentences: doc = nlp(sentence) svg = displacy.render(doc, style='dep') file_name = '-'.join([w.text for w in doc if not w.is_punct]) + '.svg' output_path = Path('/images/' + file_name) output_path.open('w', encoding='utf-8').write(svg)

The above code will generate the dependency visualizations and them to two files, This-is-an-example.svg and This-is-another-one.svg.

Using displaCy in Jupyter notebooks

displaCy is able to detect whether you're working in a Jupyter notebook, and will return markup that can be rendered in a cell straight away. When you export your notebook, the visualizations will be included as HTML.

Jupyter Example

# don't forget to install a model, e.g.: spacy download en import spacy from spacy import displacy doc = nlp(u'Rats are various medium-sized, long-tailed rodents.') displacy.render(doc, style='dep') doc2 = nlp(LONG_NEWS_ARTICLE) displacy.render(doc2, style='ent')
Example of using the displaCy dependency and named entity visualizer in a Jupyter notebook

Internally, displaCy imports display and HTML from IPython.core.display and returns a Jupyter HTML object. If you were doing it manually, it'd look like this:

from IPython.core.display import display, HTML

html = displacy.render(doc, style='dep')
return display(HTML(html))

Rendering data manually

You can also use displaCy to manually render data. This can be useful if you want to visualize output from other libraries, like NLTK or SyntaxNet. Simply convert the dependency parse or recognised entities to displaCy's format and set manual=True on either render() or serve().

DEP input

{ 'words': [ {'text': 'This', 'tag': 'DT'}, {'text': 'is', 'tag': 'VBZ'}, {'text': 'a', 'tag': 'DT'}, {'text': 'sentence', 'tag': 'NN'}], 'arcs': [ {'start': 0, 'end': 1, 'label': 'nsubj', 'dir': 'left'}, {'start': 2, 'end': 3, 'label': 'det', 'dir': 'left'}, {'start': 1, 'end': 3, 'label': 'attr', 'dir': 'right'}] }

ENT input

{ 'text': 'But Google is starting from behind.', 'ents': [{'start': 4, 'end': 10, 'label': 'ORG'}], 'title': None }

Using displaCy in a web application

If you want to use the visualizers as part of a web application, for example to create something like our online demo, it's not recommended to simply wrap and serve the displaCy renderer. Instead, you should only rely on the server to perform spaCy's processing capabilities, and use displaCy.js to render the JSON-formatted output.

The parse_deps function takes a Doc object and returns a dictionary in a format that can be rendered by displaCy.

Example

import spacy from spacy import displacy nlp = spacy.load('en') def displacy_service(text): doc = nlp(text) return displacy.parse_deps(doc)

Using a library like Falcon or Hug, you can easily turn the above code into a simple REST API that receives a text and returns a JSON-formatted parse. In your front-end, include displacy.js and initialise it with the API URL and the ID or query selector of the container to render the visualisation in, e.g. '#displacy' for <div id="displacy">.

script.js

var displacy = new displaCy('http://localhost:8080', { container: '#displacy' }) function parse(text) { displacy.parse(text); }

When you call parse(), it will make a request to your API, receive the JSON-formatted parse and render it in your container. To create an interactive experience, you could trigger this function by a button and read the text from an <input> field.