在 Matplotlib 中显示中文标签可能需要对字体和编码进行适当的配置,这是因为 Matplotlib 默认使用的是英文环境下的字体,这些字体通常不包含中文字符。要解决这个问题,你通常需要做两件事情:
-
设置 Matplotlib 使用支持中文的字体。确保你的系统中有支持中文的字体,例如
SimHei
(宋体)或Microsoft YaHei
(微软雅黑)。然后在你的脚本开始处设置这个字体。 -
确保你的环境编码是 UTF-8,这是处理中文字符串的标准编码方式。
以下是如何在 Python 脚本中设置 Matplotlib 以正确显示中文的示例代码:
import matplotlib.pyplot as plt
import networkx as nx
# 设置 matplotlib 使用的字体为 SimHei 字体,这样就可以显示中文标签了
plt.rcParams['font.sans-serif']=['SimHei']
plt.rcParams['axes.unicode_minus']=False
def draw_hierarchy():
G = nx.DiGraph()
# 添加节点并设定层级属性
G.add_node("店长", level=0)
G.add_nodes_from(["大队长1", "大队长2", "大队长3"], level=1)
G.add_nodes_from(["小队长1", "小队长2", "小队长3", "小队长4"], level=2)
G.add_nodes_from(["会员1", "会员2", "会员3", "会员4", "会员5"], level=3)
# 添加边,构建层级关系
G.add_edge("店长", "大队长1")
G.add_edge("店长", "大队长2")
G.add_edge("店长", "大队长3")
G.add_edge("大队长1", "小队长1")
G.add_edge("大队长1", "小队长2")
G.add_edge("大队长2", "小队长3")
G.add_edge("大队长3", "小队长4")
G.add_edge("小队长1", "会员1")
G.add_edge("小队长1", "会员2")
G.add_edge("小队长2", "会员3")
G.add_edge("小队长3", "会员4")
G.add_edge("小队长4", "会员5")
# 使用matplotlib绘制图形
pos = nx.multipartite_layout(G, subset_key="level")
labels = {node: node for node in G.nodes()}
nx.draw(G, pos, with_labels=True, labels=labels, node_color='lightblue', node_size=3000, font_size=10,
edge_color='gray', arrowsize=20)
plt.title('组织结构图')
plt.show()
draw_hierarchy()
在上述代码中,我们使用了 plt.rcParams
来设置字体为 SimHei
,并且禁用了负号的 Unicode 处理,因为这在中文环境中通常是不必要的。这样修改之后,你应该能在图中看到正确的中文标签。
如果上述设置仍然无法解决问题,请确认你的系统是否安装了相应的中文字体,以及你的 Python 环境是否正确识别了该字体。在某些情况下,可能需要重启 Jupyter Notebook 或 IDE 才能生效。