Skip to main content
 首页 » 编程设计

Python 在 matplotlib 中的两个列表之间创建字图以显示列表的共性

2025年05月04日21qq号

假设我有两个单词列表,

list1 = ['Cat', 'Dog', 'Elephant', 'Giraffe' 'Monkey'] 
list2 = ['Cat', 'Dog', 'Eagle', 'Elephant', 'Monkey'] 

我想创建一个如下所示的图:

Cat     ->  Cat 
Dog     ->  Dog 
Elephant \  Eagle 
Giraffe   > Elephant 
Monkey   -> Monkey 

基本上,一个单词“梯子”用箭头连接两个列表之间的每个常用单词。如果 list1 中的给定单词在 list2 中没有对应词(如示例中的 Eagle 和 Giraffe),则不需要箭头。

我不知道有什么方法可以在 matplotlib 中执行此操作。有谁知道如何在 matplotlib 中执行此操作(可能与 networkx 结合使用?)?如果该图适用于任意数量的列表(例如使用另一组连接 list2 和 list3 的箭头等),则可获得加分。

请您参考如下方法:

我认为将数据放入基于图形的表示中是解决所描述问题的好方法,但也许您的用例中这种方法过于繁重。在前者,@xg.pltpy 已经提出了建议。

这是一种仅在 matplotlib 中完成的方法,使用强大的 annotate功能。

import matplotlib.pyplot as plt 
 
# define drawing of the words and links separately. 
def plot_words(wordlist, col, ax): 
    bbox_props = dict(boxstyle="round4,pad=0.3", fc="none", ec="b", lw=2) 
    for i, word in enumerate(wordlist): 
        ax.text(col, i, word, ha="center", va="center", 
                size=12, bbox=bbox_props) 
 
def plot_links(list1, list2, cols, ax): 
    connectionstyle = "arc3,rad=0" 
    for i, word in enumerate(list1): 
        try: # do we need an edge? 
            j = list2.index(word) 
        except ValueError: 
            continue # move on to the next word 
 
        # define coordinates (relabelling here for clarity only) 
        y1, y2 = i, j 
        x1, x2 = cols 
        # draw a line from word in 1st list to word in 2nd list 
        ax.annotate("", xy=(x2, y2), xycoords='data', 
                    xytext=(x1, y1), textcoords='data', 
                    arrowprops=dict( 
                        arrowstyle="->", color="k", lw=2, 
                        shrinkA=25, shrinkB=25, patchA=None, patchB=None, 
                        connectionstyle=connectionstyle,)) 
 
 
 
# define several lists 
list1 = ['Cat', 'Dog', 'Elephant', 'Giraffe', 'Monkey'] 
list2 = ['Cat', 'Dog', 'Eagle', 'Elephant', 'Monkey'] 
list3 = ['Cat', 'Mouse', 'Horse', 'Elephant', 'Monkey'] 
 
 
# now plot them all -- words first then links between them 
plt.figure(1); plt.clf() 
fig, ax = plt.subplots(num=1) 
 
plot_words(list1, col=1, ax=ax) 
plot_words(list2, col=2, ax=ax) 
plot_words(list3, col=0, ax=ax) 
plot_links(list1, list2, ax=ax, cols=[1,2]) 
plot_links(list1, list3, ax=ax, cols=[1,0]) 
 
ax.set_xlim(-0.5, 2.5) 
ax.set_ylim(-0.5, len(list1)+0.5) 

箭头类型有很多选项,请参阅 demo .

在 arrowprops 中提供 patchA 和 patchB 参数会更清晰,因为 annotate 然后会自动剪裁箭头长度以避免补丁(这里是单词)。我把它留给读者作为练习 ;)