Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python 3.x - matplotlib: annotate plot with Emoji labels

I'm using Python 3.4 in macOS. Matplotlib is supposed to support Unicode in labels, but I'm not seeing Emojis rendered properly.

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

A few of the old pre-Unicode Emojis show up in their old style, but the rest (in this example, "fire," "music," and others) don't. Is there a trick to make these appear properly?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You problem here is that the default font have no good support for emojis.

In plt.annotate function, you can add a parameter fontname to specify the typeface that has a good support for emojis.

Following code are what I got on my Windows machine with some edits to your code, it seems that "Segoe UI Emoji" has been installed on my computer already.

# 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()

Here is what I got, the emojis may not show clearly, it depends on your typeface: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...