Text matching visualizations in Python

Question:

How could I make an image like this:

desired

Stuff I have tried: Matplotlib, Seaborn, Plotly, but all are for graphing data and not as much making visualizations given a list of linkages (such as matchings = [('The', 'The'), ('over', 'above'), ('face', 'wall')] for example). However I get stuff like:
bad
which is not as aesthetically pleasing as the above example.

Asked By: Coder

||

Answers:

Not sure if there is a matplotlib function that directly does that but you can create one in a few lines by using text boxes.

import matplotlib.pyplot as plt

def pairings(col_l,col_r,links):
  fig=plt.figure(figsize=(12,10))

  #Create vertical spacing and text boxes
  step_l=1./len(col_l)
  step_r=1./len(col_r)
  t_l =[plt.text(0.25, 0.9-step_l*i,str(l),ha='center',va='center',bbox=dict(boxstyle="round",fc='lightsteelblue'),size=30) for i,l in enumerate(col_l)] #left column
  t_r =[plt.text(0.75, 0.9-step_r*i,str(r),ha='center',va='center', bbox=dict(boxstyle="round",fc='bisque'),size=30) for i,r in enumerate(col_r)] #right column
  
  #create links
  [plt.plot([0.25,0.75],[0.9-step_l*i,0.9-step_r*v],color='slateblue',lw=5) for i,v in enumerate(links) if v!=-1]
  
  #optimize layout
  plt.xlim([0,1])
  plt.ylim([0,1])
  plt.xticks([])
  plt.yticks([])
  plt.show()

col_l is the list of all texts in the left columns. col_r is the same for the right column. And links shows for each element of the left column the index of the element of the right column linked to it. -1 means no link

For instance:

pairings(['The','fox','jumps','over','the','fence'],['The','dog','above','the','wall','jumps'],[0,-1,5,2,3,4])

returns:

enter image description here

Answered By: jylls
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.