matplotlib:用表情符号标签注释绘图

sud*_*udo 3 matplotlib python-3.x

我在 macOS 中使用 Python 3.4。Matplotlib 应该支持标签中的 Unicode,但我没有看到表情符号正确呈现。

import matplotlib.pyplot as plt
# some code to generate `data` and `labels`...
plt.clf()
plt.scatter(data[:, 0], data[:, 1], c=col)
# disclaimer: labeling taken from example http://stackoverflow.com/questions/5147112/matplotlib-how-to-put-individual-tags-for-a-scatter-plot
for label, x, y in zip(labels, data[:, 0], data[:, 1]):
    plt.annotate(
        label, # some of these contain Emojis
        xy=(x, y), xytext=(-20, 20),
        textcoords='offset points', ha='right', va='bottom',
        bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),
        arrowprops=dict(arrowstyle = '->', connectionstyle='arc3,rad=0'))
plt.show(False)
Run Code Online (Sandbox Code Playgroud)

结果

一些旧的 Unicode 之前的表情符号以旧样式显示,但其余的(在本例中为“火”、“音乐”等)则不然。有什么技巧可以让这些正确显示吗?

Fei*_*shi 5

这里的问题是默认字体对表情符号没有很好的支持。

\n\n

plt.annotate函数中,你可以添加一个参数fontname来指定对表情符号有良好支持的字体。

\n\n

以下代码是我在 Windows 计算机上获得的代码,并对您的代码进行了一些编辑,看来“Segoe UI Emoji”已经安装在我的计算机上。

\n\n
# this line is for jupyter notebook\n%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n# config the figure for bigger and higher resolution\nplt.rcParams["figure.figsize"] = [12.0, 8.0]\nplt.rcParams[\'figure.dpi\'] = 300\ndata = np.random.randn(7, 2)\nplt.scatter(data[:, 0], data[:, 1])\nlabels = \'        \xe2\x98\xba\xef\xb8\x8f  \'.split()\nprint(labels)\nfor label, x, y in zip(labels, data[:, 0], data[:, 1]):\n    plt.annotate(\n        label, # some of these contain Emojis\n        xy=(x, y), xytext=(-20, 20),\n        textcoords=\'offset points\', ha=\'right\', va=\'bottom\',\n        bbox=dict(boxstyle=\'round,pad=0.5\', fc=\'yellow\', alpha=0.5),\n        arrowprops=dict(arrowstyle = \'->\', connectionstyle=\'arc3,rad=0\'),\n        fontname=\'Segoe UI Emoji\', # this is the param added\n        fontsize=20)\nplt.show()\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是我得到的,表情符号可能无法清晰显示,这取决于您的字体:\n在此输入图像描述

\n