【问题标题】:matplotlib: annotate plot with Emoji labelsmatplotlib:用 Emoji 标签注释绘图
【发布时间】:2017-09-11 04:31:57
【问题描述】:

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

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)

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

【问题讨论】:

    标签: python-3.x matplotlib


    【解决方案1】:

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

    plt.annotate函数中,可以添加参数fontname来指定对emojis有良好支持的字体。

    以下代码是我在我的 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 的警告:github.com/matplotlib/matplotlib/issues/4492
    • 很抱歉这个错误仍未解决。也许有时您可以尝试另一个开发平台。当某些东西在我的 Windows 中无法正常运行时,我会在 Linux 上进行尝试。
    • 是的,在这些方面,Linux 往往是最受支持的平台。我使用 Linux VM 但没有显示器,更喜欢将 GUI 的东西放在 Mac 端。即使安装了 Ubuntu 桌面,我也必须找到支持最新表情符号的字体。
    猜你喜欢
    • 2017-08-26
    • 2020-01-23
    • 2016-08-20
    • 1970-01-01
    • 2021-03-14
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    相关资源
    最近更新 更多