slothfulwave612
slothfulwave612

Reputation: 1409

Plotting text using TextArea and AnnotationBbox in matplotlib

I am trying to plot text using TextArea and AnnotationBbox in matplotlib.

The resultant text that my code should plot looks like this:

enter image description here

Here is the code that I am using:

import numpy as np 
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea, HPacker, VPacker

fig, ax = plt.subplots(figsize=(12,8))

ybox1 = TextArea("Premier League Standing 2019/20 \n", 
                 textprops=dict(color="k", size=15, ha='center',va='center'))
ybox2 = TextArea("Liverpool", 
                    textprops=dict(color="crimson", size=15,ha='center',va='center'))
ybox3 = TextArea("Man City", 
                    textprops=dict(color="skyblue", size=15,ha='center',va='center'))
ybox4 = TextArea("and", 
                    textprops=dict(color="k", size=15,ha='center',va='center'))
ybox5 = TextArea("Chelsea", 
                    textprops=dict(color="blue", size=15,ha='center',va='center'))

ybox = HPacker(children=[ybox1, ybox2, ybox3, ybox4, ybox5],align="center", pad=0, sep=2)

text = AnnotationBbox(ybox, (0.5, 0.5), frameon=False)
ax.add_artist(text)

plt.show()

And it is producing below plot enter image description here

What should I add/update/change in my code so that the code produces desired result.

Upvotes: 2

Views: 1397

Answers (1)

tsj
tsj

Reputation: 792

Changed the horizontal alignments, removed newline in first box, increased pad, used VPacker. Result:

HPacker

Code:

import numpy as np 
import matplotlib.pyplot as plt
from matplotlib.offsetbox import AnnotationBbox, TextArea, HPacker, VPacker

fig, ax = plt.subplots(figsize=(12,8))

ybox1 = TextArea("Premier League Standing 2019/20", 
                 textprops=dict(color="k", size=15, ha='left',va='baseline'))

ybox2 = TextArea("Liverpool", 
                    textprops=dict(color="crimson", size=15, ha='left',va='baseline'))
ybox3 = TextArea("Man City", 
                    textprops=dict(color="skyblue", size=15, ha='left',va='baseline'))
ybox4 = TextArea("and", 
                    textprops=dict(color="k", size=15, ha='left',va='baseline'))
ybox5 = TextArea("Chelsea", 
                    textprops=dict(color="blue", size=15, ha='left',va='baseline'))

yboxh = HPacker(children=[ybox2, ybox3, ybox4, ybox5], align="left", pad=0, sep=4)
ybox = VPacker(children=[ybox1, yboxh], pad=0, sep=4)

text = AnnotationBbox(ybox, (0.5, 0.5), frameon=False)
ax.add_artist(text)

plt.show()

Upvotes: 4

Related Questions