Sub topic 8
Seeing the tree with displaCy
This chapter assumes you can load a pipeline with spacy.load, that you have read token.dep_ and token.head, and that you know the difference between pos_ and tag_. Here you will draw a dependency parse, change how the drawing looks, save it, and use it to check a parse by eye.
What displaCy is
displaCy is spaCy's built-in visualizer. For dependency parses it draws each token on a line, with curved arrows between tokens. Every arrow is one value of token.dep_. The drawing adds no information that the Doc does not already hold. It shows the same head and dep_ values you printed in earlier chapters.
Rendering a parse
displacy.render with style="dep" returns the picture as a string of SVG markup. SVG is a text-based image format that browsers open directly.
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
svg = displacy.render(doc, style="dep", jupyter=False)
print(svg[:60])The printed text starts with <svg. That output is correct, because the function returns markup and does not draw anything itself. In a Jupyter notebook, call displacy.render(doc, style="dep") as the last line of a cell. With the default jupyter=None, spaCy detects the notebook and displays the picture.
To keep the image, write the string to a file:
from pathlib import Path
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
svg = displacy.render(doc, style="dep", jupyter=False)
Path("parse.svg").write_text(svg, encoding="utf-8")
print("saved", Path("parse.svg").resolve())Open parse.svg in any browser. Pass encoding="utf-8" because the SVG can contain non-ASCII text, and some platforms do not default to UTF-8.
Reading the picture
Each word sits on a baseline with its part-of-speech label under it. The arrows follow these rules:
- An arrow starts at the head and ends at the dependent. The arrowhead points to the dependent.
- The label on the arrow is the dependent's
dep_value. - The token with no incoming arrow is the sentence root. Its
dep_isROOT, and itsheadis itself. - A tall arc spans more tokens than a short one. A long arc often marks a long-distance relation, or a parse error.
For the example sentence, a small English model typically produces the tree below. Your exact labels can differ by model version.
You can reproduce this tree as text, which is useful for comparing with the picture:
import spacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The quick brown fox jumps over the lazy dog.")
for token in doc:
print(f"{token.head.text:>6} --{token.dep_}--> {token.text}")Options that change the drawing
Pass an options dictionary to render. These are the ones you will use most often.
| Option | Default | Effect |
|---|---|---|
| `compact` | `False` | Draws a tighter layout with smaller, simpler arrows. |
| `collapse_punct` | `True` | Attaches punctuation to its head so it does not get its own arrow. |
| `collapse_phrases` | `False` | Merges each noun phrase into one box. |
| `fine_grained` | `False` | Shows `tag_` under each word instead of `pos_`. |
| `add_lemma` | `False` | Adds each token's lemma under the word. |
| `distance` | `175` | Pixels between words. Lower it to fit long sentences. |
| `bg`, `color`, `font` | white, black, Arial | Background colour, text colour, and font. |
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The committee approved the new budget.")
options = {
"compact": False,
"fine_grained": True,
"add_lemma": True,
"distance": 120,
"bg": "#fafafa",
"color": "#1a1a1a",
}
svg = displacy.render(doc, style="dep", options=options, jupyter=False)
print(len(svg) > 0)With fine_grained=True the labels under the words come from tag_, such as NNS or VBD. Without it they come from pos_, such as NOUN or VERB. This is a quick way to confirm that the picture and your printed attributes agree.
Several sentences and long text
A diagram is as wide as the sentence is long. A 40-token sentence becomes a very wide image that is hard to read. Two habits help:
- Render one sentence at a time by passing the spans from
doc.sents. displaCy converts each span into its own small Doc. - Lower
distance, or setcompact=True.
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp(
"Researchers published the dataset. "
"The editors reviewed the paper before the deadline."
)
sentences = list(doc.sents)
svg = displacy.render(sentences, style="dep", options={"compact": True}, jupyter=False)
print(len(sentences), "sentences,", svg.count("<svg"), "svg elements")When you pass a list, render returns all the drawings joined into one string. Sentence boundaries come from the parser, so a wrong boundary also shows up as a wrongly cut diagram. That is a useful check in its own right.
Serving the page
Outside a notebook, displacy.serve starts a small local web server and shows the diagram in your browser.
import spacy
from spacy import displacy
nlp = spacy.load("en_core_web_sm")
doc = nlp("The engineer fixed the bug.")
displacy.serve(doc, style="dep", port=5000)The call blocks until you press Ctrl+C, so do not put it in the middle of a script that must continue. If the port is already in use, choose another with port=. For a file you can share, prefer render(..., page=True), which wraps the SVG in a full HTML page that you can write to disk.
Drawing a tree you built yourself
Manual mode accepts a dictionary and does not need a pipeline. Use it to draw a gold-standard parse from a dataset, or to draw a diagram for teaching.
from spacy import displacy
parse = {
"words": [
{"text": "Fish", "tag": "NOUN"},
{"text": "swim", "tag": "VERB"},
],
"arcs": [
{"start": 0, "end": 1, "label": "nsubj", "dir": "left"},
],
}
svg = displacy.render(parse, style="dep", manual=True, jupyter=False)
print(svg[:40])Here start and end are token indexes, with start smaller than end. dir says which end the arrowhead points to. With "left" the arrowhead is at the earlier token, so Fish is the dependent of swim.
Common errors
- Empty or arc-less diagrams. If the pipeline has no parser, spaCy warns that the Doc has no dependency annotation. Check
nlp.pipe_namesfor"parser", and do not disable it for this task. - Seeing markup instead of a picture. In a plain script,
renderreturns a string. Print it to a file, not to the terminal. - Confusing
pos_withtag_in the picture. The default label is the coarse tag. Turn onfine_grainedwhen you need the detailed one. - Trusting a clean-looking picture. A neat diagram can still be wrong. The renderer draws whatever the model predicted.
- Script hangs.
displacy.servenever returns. Userenderwhen you only want the SVG.
Exercise
You render a long sentence with displacy.render(doc, style="dep") and the SVG is too wide to read. Name two changes that make it narrower. Also say how you would show the fine-grained tags under each word.
Show answer
Render one sentence at a time with displacy.render(list(doc.sents), style="dep"), and set options such as {"compact": True} or a smaller "distance" value. To show fine-grained tags, pass options={"finegrained": True}, which labels each word with tag instead of pos_.