图形工具绘制功能无法显示中文文本

时间:2018-01-19 02:44:48

标签: python draw graph-tool

我正在使用图形工具并尝试绘制具有中文单词节点属性的图形。 但是,当我使用

绘制它时
# coding=utf-8
from graph_tool.all import *

# English string as vertex name
g = Graph(directed=False)
vprop_name = g.new_vertex_property("string")
eprop_name = g.new_edge_property("string")
g.vertex_properties["name"] = vprop_name
g.edge_properties["name"] = eprop_name

v1 = g.add_vertex()
v2 = g.add_vertex()
v3 = g.add_vertex()
e1 = g.add_edge(0, 1)
e2 = g.add_edge(0, 2)
vprop_name[v1] = "cat"
vprop_name[v2] = "dog"
vprop_name[v3] = "mouse"
eprop_name[e1] = "01"
eprop_name[e2] = "02"

graph_draw(g, vertex_text=g.vertex_properties["name"],
           vertex_color="blue",
           vertex_font_size=18,
           edge_text=g.edge_properties["name"],
           output_size=(300, 300),
           output="english.png")

# Chinese string as vertex name
g = Graph(directed=False)
vprop_name = g.new_vertex_property("string")
eprop_name = g.new_edge_property("string")
g.vertex_properties["name"] = vprop_name
g.edge_properties["name"] = eprop_name

v1 = g.add_vertex()
v2 = g.add_vertex()
v3 = g.add_vertex()
e1 = g.add_edge(0, 1)
e2 = g.add_edge(0, 2)
vprop_name[v1] = "猫"
vprop_name[v2] = "狗"
vprop_name[v3] = "老鼠"
eprop_name[e1] = "01"
eprop_name[e2] = "02"

graph_draw(g, vertex_text=g.vertex_properties["name"],
           vertex_color="blue",
           vertex_font_size=18,
           edge_text=g.edge_properties["name"],
           output_size=(300, 300),
           output="chinese.png")

当“名称”属性是中文文本时,它不能显示任何单词。 当文字是英文时,数​​字没问题。

这是“english.png”: enter image description here

这是“chinese.png”的结果: enter image description here

所以我想知道如何使用这个功能让它显示中文文本。

1 个答案:

答案 0 :(得分:2)

图形工具使用cairo进行字体渲染,这有点原始。这意味着您需要手动选择支持中文字符的字体:

graph_draw(g, vertex_text=g.vertex_properties["name"],
           vertex_color="blue",
           vertex_font_size=18,
           vertex_font_family="HAN NOM A",        # this font needs to be installed
           edge_text=g.edge_properties["name"],
           output="chinese.png")

上面给了我:

enter image description here