matplotlib:使用Emoji标签注释绘图

3

我在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 https://dev59.com/3G435IYBdhLWcg3w50f4
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)

result

一些旧的Unicode表情符号以其旧样式出现,但其他表情符号(例如“火”,“音乐”等)则不会。有什么技巧可以使它们正确显示吗?

1个回答

5
您的问题在于默认字体对表情符号的支持不够好。
plt.annotate函数中,您可以添加一个参数fontname来指定支持表情符号的字体。
以下是我在Windows机器上使用您的代码进行了一些编辑后得到的代码,似乎我的计算机已经安装了"Segoe UI Emoji"字体。
# this line is for jupyter notebook
%matplotlib inline

import matplotlib.pyplot as plt
import numpy as np
# config the figure for bigger and higher resolution
plt.rcParams["figure.figsize"] = [12.0, 8.0]
plt.rcParams['figure.dpi'] = 300
data = np.random.randn(7, 2)
plt.scatter(data[:, 0], data[:, 1])
labels = '        ☺️  '.split()
print(labels)
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'),
        fontname='Segoe UI Emoji', # this is the param added
        fontsize=20)
plt.show()

这是我收到的内容,表情符号可能显示不清楚,这取决于您使用的字体: 输入图像描述


谢谢,这回答了我的问题。不幸的是,在OS X中它不能直接使用,所以我现在使用Bokeh(它有优点和缺点)来绘制这个图表。我搜索并在这里找到了针对OSX的特定注意事项:https://github.com/matplotlib/matplotlib/issues/4492 - sudo
很抱歉这个 bug 还没有解决。也许你可以尝试另一个开发平台。当一些东西在我的 Windows 上无法正常工作时,我会在 Linux 上试试。 - Feishi
是的,当涉及到这些事情时,Linux往往是最受支持的平台。我使用一个没有显示器的Linux虚拟机,更喜欢将GUI事务保留在Mac端。即使使用Ubuntu桌面安装,我也必须去找一个支持最新表情符号的字体。 - sudo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接