Matplotlib: Annotated Emoji Label Story

I am using Python 3.4 on macOS. Matplotlib is supposed to support Unicode in shortcuts, but I don't see Emojis display correctly.

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)

result

Some of the old pre-installed Unicode Emojis appear in their old style, but others (in this example, “fire”, “music” and others) do not. Is there a trick to make them look right?

+2
source share
1 answer

The problem is that the default font does not have good support for emojis.

In a function, plt.annotateyou can add a parameter fontnameto indicate a font that has good support for 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()

, emojis , : enter image description here

+3

Source: https://habr.com/ru/post/1688706/


All Articles