How to use Font Awesome symbol as marker in matplotlib - python

Is it possible to use a font-awesome icon as a marker in a scatterplot with matplotlib?
Or is it possible to use it as a font and put the icon as a 'text'?
This question has originally been asked here, but has been closed for an unknown reason. Since I consider it a valid and useful problem, which hasn't been addressed anywhere on Stackoverflow and sure deserves an answer, I will simply ask it again.

FontAwesome is available from here.
It provides its icons as vector graphics and as well as as otf-font.
Use FontAwesome otf font
Matplotlib cannot natively read vector graphics, but it can load otf-fonts.
After downloading the FontAwesome package you can access the font via a matplotlib.font_manager.FontProperties object, e.g.
fp = FontProperties(fname=r"C:\Windows\Fonts\Font Awesome 5 Free-Solid-900.otf")
Create texts
The FontProperties can be the input for matplotlib text objects
plt.text(.6, .4, "\uf16c", fontproperties=fp)
Unfortunately, using the FontAwesome ligatures is not possible. Hence the individual symbols need to be accessed via their UTF8 key. This is a little cumbersome, but the cheatsheet can come handy here. Storing those needed symbols in a dictionary with a meaningful name may make sense.
Example:
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
fp1 = FontProperties(fname=r"C:\Windows\Fonts\Font Awesome 5 Brands-Regular-400.otf")
fp2 = FontProperties(fname=r"C:\Windows\Fonts\Font Awesome 5 Free-Solid-900.otf")
symbols = dict(cloud = "\uf6c4", campground = "\uf6bb", hiking = "\uf6ec",
mountain = "\uf6fc", tree = "\uf1bb", fish = "\uf578",
stackoverflow = "\uf16c")
fig, (ax, ax2) = plt.subplots(ncols=2, figsize=(6.2, 2.2), sharey=True)
ax.text(.5, .5, symbols["stackoverflow"], fontproperties=fp1, size=100,
color="orange", ha="center", va="center")
ax2.stackplot([0,.3,.55,.6,.65,1],[.1,.2,.2,.2,.2,.15],[.3,.2,.2,.3,.2,.2],
colors=["paleturquoise", "palegreen"])
ax2.axis([0,1,0,1])
ax2.text(.6, .4, symbols["mountain"], fontproperties=fp2, size=16, ha="center")
ax2.text(.09, .23, symbols["campground"], fontproperties=fp2, size=13)
ax2.text(.22, .27, symbols["hiking"], fontproperties=fp2, size=14)
ax2.text(.7, .24, symbols["tree"], fontproperties=fp2, size=14,color="forestgreen")
ax2.text(.8, .33, symbols["tree"], fontproperties=fp2, size=14,color="forestgreen")
ax2.text(.88, .28, symbols["tree"], fontproperties=fp2, size=14,color="forestgreen")
ax2.text(.35, .03, symbols["fish"], fontproperties=fp2, size=14,)
ax2.text(.2, .7, symbols["cloud"], fontproperties=fp2, size=28,)
plt.show()
Create markers
Creating a lot of texts like above is not really handy. To have the icons as markers would be nicer for certain applications. Matplotlib does have the ability to use utf symbols as markers, however, only through the mathtext functionality. Getting an otf font to be used as mathfont in matplotlib was unsuccessful in my trials.
An alternative is to create a matplotlib.path.Path from the symbol. This can be done via a matplotlib.textpath.TextToPath instance, which is unfortunately undocumented. The TextToPath has a method get_text_path taking a fontproperty and a string as input and returning the vertices and codes from which to create a Path. A Path can be used as a marker, e.g. for a scatter plot.
v, codes = TextToPath().get_text_path(fp, \uf6fc)
path = Path(v, codes, closed=False)
plt.scatter(..., marker=path)
Some example:
import numpy as np; np.random.seed(32)
from matplotlib.path import Path
from matplotlib.textpath import TextToPath
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
fp = FontProperties(fname=r"C:\Windows\Fonts\Font Awesome 5 Free-Solid-900.otf")
symbols = dict(cloud = "\uf6c4", campground = "\uf6bb", hiking = "\uf6ec",
mountain = "\uf6fc", tree = "\uf1bb", fish = "\uf578",
stackoverflow = "\uf16c")
fig, ax = plt.subplots()
def get_marker(symbol):
v, codes = TextToPath().get_text_path(fp, symbol)
v = np.array(v)
mean = np.mean([np.max(v,axis=0), np.min(v, axis=0)], axis=0)
return Path(v-mean, codes, closed=False)
x = np.random.randn(4,10)
c = np.random.rand(10)
s = np.random.randint(120,500, size=10)
plt.scatter(*x[:2], s=s, c=c, marker=get_marker(symbols["cloud"]),
edgecolors="none", linewidth=2)
plt.scatter(*x[2:], s=s, c=c, marker=get_marker(symbols["fish"]),
edgecolors="none", linewidth=2)
plt.show()

Adding to ImportanceOfBeingErnest's great answer: you can easily get the UTF keys by using the fontawesome Python package.
Install via pip:
pip install fontawesome
Usage:
import fontawesome as fa
# icons dict converts to correct utf-8 code:
fa.icons['thumbs-up']

Related

Is there any way to plot emojis in matplotlib?

Does anybody know how to plot emojis in matplotlib while using windows? I've been struggling to find a solution as most out there seem to be specific for macOS.
Below is my current graph showing emojis plotted in a vector space, but as usual most do not show up.
Is there perhaps any fonts already installed with matplotlib that provide emoji support or will I need to install some backend solutions?
Code:
def display_pca_scatterplot(model, words=None, sample=0):
if words == None:
if sample > 0:
words = np.random.choice(list(model.vocab.keys()), sample)
else:
words = [ word for word in model.vocab ]
prop = FontProperties(fname='/usr/share/fonts/truetype/noto/Apple Color Emoji.ttc')
word_vectors = np.array([model[w] for w in words])
twodim = PCA().fit_transform(word_vectors)[:,:2]
sb.set_style("darkgrid")
plt.figure(figsize=(10,10))
plt.scatter(twodim[:,0], twodim[:,1]) #, edgecolors='w', color='w')
for word, (x,y) in zip(words, twodim):
plt.text(x+0.0, y+0.0, word, fontsize=20) #fontproperties=prop)
This seems to work for me , but apparently depends on default fonts (eg "Segoe UI Emoji") being installed:
plt.text(0,.5,'πŸ˜€ πŸ˜ƒ πŸ˜„ 😁 πŸ˜† πŸ˜… πŸ˜‚ 🀣 ☺️ 😊 πŸ˜‡',fontsize=20)
i have created a small library (imojify) to deal with that issue
from imojify import imojify
from matplotlib import pyplot as plt
from matplotlib.offsetbox import OffsetImage,AnnotationBbox
def offset_image(cords, emoji, ax):
img = plt.imread(imojify.get_img_path(emoji))
im = OffsetImage(img, zoom=0.08)
im.image.axes = ax
ab = AnnotationBbox(im, (cords[0], cords[1]), frameon=False, pad=0)
ax.add_artist(ab)
emjis = ['πŸ˜‚', '🀣', 'πŸ˜”', '😏','😍', 'πŸ₯°', '😘']
values =[30, 50, 15, 29, 15, 50, 12]
fig, ax = plt.subplots(figsize=(12,8))
ax.bar(range(len(emjis)), values, width=0.5,align="center")
ax.set_xticks(range(len(emjis)))
ax.set_xticklabels([])
ax.tick_params(axis='x', which='major', pad=26)
ax.set_ylim((0, ax.get_ylim()[1]+10))
for i, e in enumerate(emjis):
offset_image([i,values[i]+5], e, ax)
the library contains images for all emojis,
imojify.get_img_path(emoji) simply returns the path of the emoji image then you can use OffsetImage to add these images as labels

Failed to change matplotlib default font [duplicate]

I have been trying to use matplotlib's text or annotate modules with mandarin Chinese characters. Somehow it ends up showing boxes. Any idea on this ?
Here is a solution that works for me on Python 2.7 and Python 3.3, using both text and annotate methods with Chinese.
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
fig = plt.figure()
ax = fig.add_subplot(111)
ChineseFont1 = FontProperties(fname = 'C:\\Windows\\Fonts\\simsun.ttc')
ChineseFont2 = FontProperties('SimHei')
ax.text(3, 2, u'ζˆ‘δΈ­ζ–‡ζ˜―ε†™εΎ—εˆ°ηš„', fontproperties = ChineseFont1)
ax.text(5, 1, u'ζˆ‘δΈ­ζ–‡ζ˜―ε†™εΎ—εˆ°ηš„', fontproperties = ChineseFont2)
ax.annotate(u'ζˆ‘δΈ­ζ–‡ζ˜―ε†™εΎ—εˆ°ηš„', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05),
fontproperties = ChineseFont1)
ax.axis([0, 10, 0, 10])
plt.show()
ChineseFont1 is hard coded to a font file, while ChineseFont2 grabs a font by family name (but for ChineseFont2 I had to try a couple to find one that would work). Both of those are particular to my system, in that they reference fonts I have, so you quite likely will need to change them to reference fonts/paths on your system.
The font loaded by default doesn't seem to support Chinese characters, so it was primarily a font choice issue.
Another solution is to use pgf backend which uses XeTeX. This allows one to use UTF-8 directly:
#!/usr/bin/env python2
# -*- coding:utf-8 -*-
import matplotlib
matplotlib.use("pgf")
pgf_with_custom_preamble = {
# "font.size": 18,
"pgf.rcfonts": False,
"text.usetex": True,
"pgf.preamble": [
# math setup:
r"\usepackage{unicode-math}",
# fonts setup:
r"\setmainfont{WenQuanYi Zen Hei}",
r"\setsansfont{WenQuanYi Zen Hei}",
r"\setmonofont{WenQuanYi Zen Hei Mono}",
],
}
matplotlib.rcParams.update(pgf_with_custom_preamble)
from matplotlib import pyplot as plt
x = range(5)
y = range(5)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(x, y, label=u"ζˆ‘")
ax.legend(u"δΈ­")
ax.set_xlabel(u"是")
ax.set_ylabel(u"写")
ax.set_title(u"εΎ—")
ax.text(3, 2, u'到')
ax.annotate(u'ηš„', xy=(2, 1), xytext=(3, 1),
arrowprops=dict(arrowstyle="<|-", connectionstyle="arc3", color='k'))
fig.savefig("pgf-mwe.png")
Result:
This solution requires matplotlib 1.2+ and probably XeTeX installed on Your system. The easiest way to get a working XeTeX is to go for any modern LaTeX distribution: TeXLive (available for all platforms) or MiKTeX (windows only).
matplotlib.rc('font', family='Source Han Sans CN')
ax = quarterly_gdp.plot(title='ε›½ε†…η”ŸδΊ§ζ€»ε€Ό')
example
You only have to setup font family of your matplotlib and after that you can plot with Chinese labels. I've set up font to be Source Han Sans CN, as it's the only available font on my computer for Chinese.
You can check the available font by command fc-list :lang=zh.

Matplotlib multi-colored title [duplicate]

Is there a way in matplotlib to partially specify the color of a string?
Example:
plt.ylabel("Today is cloudy.")
How can I show "today" as red, "is" as green and "cloudy." as blue?
I only know how to do this non-interactively, and even then only with the 'PS' backend.
To do this, I would use Latex to format the text. Then I would include the 'color' package, and set your colors as you wish.
Here is an example of doing this:
import matplotlib
matplotlib.use('ps')
from matplotlib import rc
rc('text',usetex=True)
rc('text.latex', preamble='\usepackage{color}')
import matplotlib.pyplot as plt
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig('test.ps')
This results in (converted from ps to png using ImageMagick, so I could post it here):
Here's the interactive version. Edit: Fixed bug producing extra spaces in Matplotlib 3.
import matplotlib.pyplot as plt
from matplotlib import transforms
def rainbow_text(x,y,ls,lc,**kw):
"""
Take a list of strings ``ls`` and colors ``lc`` and place them next to each
other, with text ls[i] being shown in color lc[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
"""
t = plt.gca().transData
fig = plt.gcf()
plt.show()
#horizontal version
for s,c in zip(ls,lc):
text = plt.text(x,y,s+" ",color=c, transform=t, **kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
#vertical version
for s,c in zip(ls,lc):
text = plt.text(x,y,s+" ",color=c, transform=t,
rotation=90,va='bottom',ha='center',**kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
plt.figure()
rainbow_text(0.05,0.05,"all unicorns poop rainbows ! ! !".split(),
['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
size=20)
Extending Yann's answer, LaTeX coloring now also works with PDF export:
import matplotlib
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
import matplotlib.pyplot as plt
pgf_with_latex = {
"text.usetex": True, # use LaTeX to write all text
"pgf.rcfonts": False, # Ignore Matplotlibrc
"pgf.preamble": [
r'\usepackage{color}' # xcolor for colours
]
}
matplotlib.rcParams.update(pgf_with_latex)
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig("test.pdf")
Note that this python script sometimes fails with Undefined control sequence errors in the first attempt. Running it again is then successful.
After trying all the methods above, I return back to my stupid but easy method, using plt.text. The only problem is that you need to adjust the spaces between each word. You may need to adjust the positions several times, but I still like this way, because it
saves you from installing tex compilers,
does not require any special backends, and
free you from configuring matplotlib rc and configure back, or it may slows down your other plots, due to usetex=True
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
label_x = -0.15
ax.text(label_x, 0.35, r"Today", color='red', rotation='vertical', transform=ax.transAxes)
ax.text(label_x, 0.5, r"is", color='green', rotation='vertical', transform=ax.transAxes)
ax.text(label_x, 0.55, r"cloudy", color='blue', rotation='vertical', transform=ax.transAxes)

How do I get 'matplotlib' to use my LaTeX sans font by default [duplicate]

The following script:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as mpl
mpl.rc('font', family='sans-serif')
mpl.rc('text', usetex=True)
fig = mpl.figure()
ax = fig.add_subplot(1,1,1)
ax.text(0.2,0.5,r"Math font: $451^\circ$")
ax.text(0.2,0.7,r"Normal font (except for degree symbol): 451$^\circ$")
fig.savefig('test.png')
is an attempt to use a sans-serif font in matplotlib with LaTeX. The issue is that the math font is still a serif font (as indicated by the axis numbers, and as demonstrated by the labels in the center). Is there a way to set the math font to also be sans-serif?
I always have text.usetex = True in my matplotlibrc file. In addition to that, I use this as well:
mpl.rcParams['text.latex.preamble'] = [
r'\usepackage{siunitx}', # i need upright \micro symbols, but you need...
r'\sisetup{detect-all}', # ...this to force siunitx to actually use your fonts
r'\usepackage{helvet}', # set the normal font here
r'\usepackage{sansmath}', # load up the sansmath so that math -> helvet
r'\sansmath' # <- tricky! -- gotta actually tell tex to use!
]
Hope that helps.
The easiest way is to use matplotlib's internal TeX, e.g.:
import pylab as plt
params = {'text.usetex': False, 'mathtext.fontset': 'stixsans'}
plt.rcParams.update(params)
If you use an external LaTeX, you can use, e.g., CM Bright fonts:
params = {'text.usetex': True,
'text.latex.preamble': [r'\usepackage{cmbright}', r'\usepackage{amsmath}']}
plt.rcParams.update(params)
Note, that the CM Bright font is non-scalable, and you'll not be able to save PDF/PS!
Same with other options with external LaTeX I've found so far.
This will enable you to use the Computer Modern Sans font if you, as I, prefer it over Helvetica:
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage[cm]{sfmath}']
mpl.rcParams['font.family'] = 'sans-serif'
mpl.rcParams['font.sans-serif'] = 'cm'

Matplotlib - Multicolour axis labels [duplicate]

Is there a way in matplotlib to partially specify the color of a string?
Example:
plt.ylabel("Today is cloudy.")
How can I show "today" as red, "is" as green and "cloudy." as blue?
I only know how to do this non-interactively, and even then only with the 'PS' backend.
To do this, I would use Latex to format the text. Then I would include the 'color' package, and set your colors as you wish.
Here is an example of doing this:
import matplotlib
matplotlib.use('ps')
from matplotlib import rc
rc('text',usetex=True)
rc('text.latex', preamble='\usepackage{color}')
import matplotlib.pyplot as plt
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig('test.ps')
This results in (converted from ps to png using ImageMagick, so I could post it here):
Here's the interactive version. Edit: Fixed bug producing extra spaces in Matplotlib 3.
import matplotlib.pyplot as plt
from matplotlib import transforms
def rainbow_text(x,y,ls,lc,**kw):
"""
Take a list of strings ``ls`` and colors ``lc`` and place them next to each
other, with text ls[i] being shown in color lc[i].
This example shows how to do both vertical and horizontal text, and will
pass all keyword arguments to plt.text, so you can set the font size,
family, etc.
"""
t = plt.gca().transData
fig = plt.gcf()
plt.show()
#horizontal version
for s,c in zip(ls,lc):
text = plt.text(x,y,s+" ",color=c, transform=t, **kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, x=ex.width, units='dots')
#vertical version
for s,c in zip(ls,lc):
text = plt.text(x,y,s+" ",color=c, transform=t,
rotation=90,va='bottom',ha='center',**kw)
text.draw(fig.canvas.get_renderer())
ex = text.get_window_extent()
t = transforms.offset_copy(text._transform, y=ex.height, units='dots')
plt.figure()
rainbow_text(0.05,0.05,"all unicorns poop rainbows ! ! !".split(),
['red', 'orange', 'brown', 'green', 'blue', 'purple', 'black'],
size=20)
Extending Yann's answer, LaTeX coloring now also works with PDF export:
import matplotlib
from matplotlib.backends.backend_pgf import FigureCanvasPgf
matplotlib.backend_bases.register_backend('pdf', FigureCanvasPgf)
import matplotlib.pyplot as plt
pgf_with_latex = {
"text.usetex": True, # use LaTeX to write all text
"pgf.rcfonts": False, # Ignore Matplotlibrc
"pgf.preamble": [
r'\usepackage{color}' # xcolor for colours
]
}
matplotlib.rcParams.update(pgf_with_latex)
plt.figure()
plt.ylabel(r'\textcolor{red}{Today} '+
r'\textcolor{green}{is} '+
r'\textcolor{blue}{cloudy.}')
plt.savefig("test.pdf")
Note that this python script sometimes fails with Undefined control sequence errors in the first attempt. Running it again is then successful.
After trying all the methods above, I return back to my stupid but easy method, using plt.text. The only problem is that you need to adjust the spaces between each word. You may need to adjust the positions several times, but I still like this way, because it
saves you from installing tex compilers,
does not require any special backends, and
free you from configuring matplotlib rc and configure back, or it may slows down your other plots, due to usetex=True
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
label_x = -0.15
ax.text(label_x, 0.35, r"Today", color='red', rotation='vertical', transform=ax.transAxes)
ax.text(label_x, 0.5, r"is", color='green', rotation='vertical', transform=ax.transAxes)
ax.text(label_x, 0.55, r"cloudy", color='blue', rotation='vertical', transform=ax.transAxes)

Categories