when I run a modified version of Matplotlib's multi page example with a tab added to the title, I get the following output:
This is my working example. The comments above the code are suggestions I found here and in Non-ASCII characters in Matplotlib, but no success so far.
# -*- coding: utf-8 -*-
import matplotlib
from matplotlib.backends.backend_pdf import PdfPages
from pylab import *
#matplotlib.rc('font', family='DejaVu Sans')
#matplotlib.rc('font', **{'sans-serif' : 'Arial',
# 'family' : 'sans-serif'})
#matplotlib.rcParams['pdf.fonttype'] = 42
#matplotlib.rcParams['ps.fonttype'] = 42
pdf = PdfPages('multipage_pdf.pdf')
figure(figsize=(3,3))
plot(range(7), [3,1,4,1,5,9,2], 'r-o')
title('Page\tOne')
savefig(pdf, format='pdf') # note the format='pdf' argument!
close()
pdf.close()
Any ideas how this could be solved?
The solution is to add
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
as mentioned here and here.
I couldn't find out which line does the magic, not all seemed to be needed in my case, but I just added all. If there is a problem with tex complaining about not being able to encode something, you might be able to comment the ['text.usetex'] with it still working.
From the matplotlib doc:
Add "pdf.use14corefonts: True" in your configuration file to use only
the 14 PDF core fonts. These fonts do not need to be embedded; every
PDF viewing application is required to have them. This results in very
light PDF files you can use directly in LaTeX or ConTeXt documents
generated with pdfTeX, without any conversion.
These fonts are: Helvetica, Helvetica-Bold, Helvetica-Oblique,
Helvetica-BoldOblique, Courier, Courier-Bold, Courier-Oblique,
Courier-BoldOblique, Times-Roman, Times-Bold, Times-Italic,
Times-BoldItalic, Symbol, ZapfDingbats.
Related
I have to make a figure in python. I need it to use the font Palatino. I downloaded the font here. I placed it under *\matplotlib\mpl-data\fonts\ttf (which turned out to be useless since I had to provide full path to make it work).
Using the following lines allows me to use the font:
prop = fm.FontProperties(fname='C:/Users/MyPC/pyApp/venv/Lib/site-packages/matplotlib/mpl-data/fonts/ttf/Palatino-Roman.ttf')
mpl.rcParams['font.family'] = prop.get_name()
Yay.
Now when I want to use Latex in matplotlib,
rc('text',usetex=True)
the font is now not the one I want. I tried to follow the official page about that and instead use:
rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
but I cannot see any difference. I tried all possibilities and it looks like the same font.
What am I doing wrong? Perhaps its the latex side that's lacking the required font package...
You can load any latex packages when using rc('text',usetex=True)
You can add this in your code:
plt.rcParams['text.latex.preamble'] = [r'\usepackage{palatino, mathpazo}']
A few days ago, I need to draw a plot by using matplotlib, since it could not display the font properly, so I
edited matplotlibrc file, unhashtag "font.family" and "font.serif".
added specific font file to ttf.
deleted .matplotlib file.
Then I code:
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif'] = ['Microsoft JhengHei']
plt.rcParams['axes.unicode_minus'] = False
Now when I tried to use "to_csv" to write the dataframe into csv, there's a
unicode problem. It ran without problem before. So I changed those 3 steps back and still have a unicode problem.
Not sure if there's any problem of my setting.
How do I set latex package options in python?
I am trying to setup siunitx. I don't understand how to set options. This also applies to the matplotlibrc directly.
The following does not work.
import matplotlib as mpl
mpl.rc('text', usetex=True)
mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single,range-phrase={-}]{siunitx}'
## using the following instead of the previous line works...
# mpl.rcParams['text.latex.preamble'] = '\usepackage[range-units = single]{siunitx},\sisetup{range-phrase={-}}'
import numpy as np
import matplotlib.pyplot as plt
x=np.linspace(1,100,1)
y=x
fig=plt.figure()
ax=fig.add_subplot(111)
ax.plot(x,y,label=r'\SIrange{0}{1}{\metre\per\second}')
ax.legend(loc=0)
Since the code snippet works, I would suggest that it is due to the use of the comma. I tried \, or ',' without luck. I tried it on Mac in a jupyter notebook.
In the default matplotlibrc it says
#text.latex.preamble : ## IMPROPER USE OF THIS FEATURE WILL LEAD TO LATEX FAILURES
## AND IS THEREFORE UNSUPPORTED. PLEASE DO NOT ASK FOR HELP
## IF THIS FEATURE DOES NOT DO WHAT YOU EXPECT IT TO.
## preamble is a comma separated list of LaTeX statements
## that are included in the LaTeX document preamble.
## An example:
## text.latex.preamble : \usepackage{bm},\usepackage{euler}
## The following packages are always loaded with usetex, so
## beware of package collisions: color, geometry, graphicx,
## type1cm, textcomp. Adobe Postscript (PSSNFS) font packages
## may also be loaded, depending on your font settings
Unfortunately I cannot find any information on the proper usage of this option besides what is specified in the comments...
Any ideas?
I would expect that it helps to enclose the preamble string in a list.
mpl.rcParams['text.latex.preamble'] = ['\usepackage[range-units=single,range-phrase={-}]{siunitx}']
I would like to produce plots using matplotlib (through anaconda-spider installed on os x yosemite) and put labels on it not interpreted by tex.
Here is the sample code:
# -*- coding: utf-8 -*-
import matplotlib.pyplot as pp
my_rc_param = {'text.usetex': False}
pp.figure()
pp.rcParams.update(my_rc_param)
pp.plot(range(10))
pp.xlabel('$x$')
I would like to see exactly the string $x$ as x label. In turn, I get the math-mode latex x.
I have also tried, unsuccessfully, to put the following preamble:
from matplotlib import rc
rc('text', usetex=False)
Is there a way to force a plain interpreter?
Or should I consider this as a bug?
You are not getting any latex mode. You are simply using the mathtex feature of matplotlib. Using latex is a different thing. I checked whether it is possible to switch off mathtex for matplotlib, and there is a quiet recent issue on this (see here). However, the way to sort out this problem consist is avoiding the math just escaping the $ symbol with '\':
pp.xlabel('\$x\$')
Just remove all the stuff related to the text.usetex as you are trying to do a complete different thing here.
I want to generate high-quality diagrams for a presentation. I’m using Python’s matplotlib to generate the graphics. Unfortunately, the PDF export seems to ignore my font settings.
I tried setting the font both by passing a FontProperties object to the text drawing functions and by setting the option globally. For the record, here is a MWE to reproduce the problem:
import scipy
import matplotlib
matplotlib.use('cairo')
import matplotlib.pylab as pylab
import matplotlib.font_manager as fm
data = scipy.arange(5)
for font in ['Helvetica', 'Gill Sans']:
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.bar(data, data)
ax.set_xticks(data)
ax.set_xticklabels(data, fontproperties = fm.FontProperties(family = font))
pylab.savefig('foo-%s.pdf' % font)
In both cases, the produced output is identical and uses Helvetica (and yes, I do have both fonts installed).
Just to be sure, the following doesn’t help either:
matplotlib.rc('font', family = 'Gill Sans')
Finally, if I replace the backend, instead using the native viewer:
matplotlib.use('MacOSX')
I do get the correct font displayed – but only in the viewer GUI. The PDF output is once again wrong.
To be sure – I can set other fonts – but only other classes of font families: I can set serif fonts or fantasy or monospace. But all sans-serif fonts seem to default to Helvetica.
Basically, #Jouni’s is the right answer but since I still had some trouble getting it to work, here’s my final solution:
#!/usr/bin/env python2.6
import scipy
import matplotlib
matplotlib.use('cairo')
import matplotlib.pylab as pylab
import matplotlib.font_manager as fm
font = fm.FontProperties(
family = 'Gill Sans', fname = '/Library/Fonts/GillSans.ttc')
data = scipy.arange(5)
fig = pylab.figure()
ax = fig.add_subplot(111)
ax.bar(data, data)
ax.set_yticklabels(ax.get_yticks(), fontproperties = font)
ax.set_xticklabels(ax.get_xticks(), fontproperties = font)
pylab.savefig('foo.pdf')
Notice that the font has to be set explicitly using the fontproperties key. Apparently, there’s no rc setting for the fname property (at least I didn’t find it).
Giving a family key in the instantiation of font isn’t strictly necessary here, it will be ignored by the PDF backend.
This code works with the cairo backend only. Using MacOSX won’t work.
The "family" argument and the corresponding rc parameter are not meant to specify the name of the font can actually be used this way. There's an (arguably baroque) CSS-like font selection system that helps the same script work on different computers, selecting the closest font available. The usually recommended way to use e.g. Gill Sans is to add it to the front of the value of the rc parameter font.sans-serif (see sample rc file), and then set font.family to sans-serif.
This can be annoying if the font manager decides for some obscure reason that Gill Sans is not the closest match to your specification. A way to bypass the font selection logic is to use FontProperties(fname='/path/to/font.ttf') (docstring).
In your case, I suspect that the MacOSX backend uses fonts via the operating system's mechanisms and so automatically supports all kinds of fonts, but the pdf backend has its own font support code that doesn't support your version of Gill Sans.
This is an addition to the answers above if you came here for a non-cairo backend.
The pdf-backend of matplotlib does not yet support true type font collections (saved as .ttc files). See this issue.
The currently suggested workaround is to extract the font-of-interest from a .ttc file and save it as a .ttf file. And then use that font in the way described by Konrad Rudolph.
You can use the python-package fonttools to achieve this:
font = TTFont("/System/Library/Fonts/Helvetica.ttc", fontNumber=0)
font.save("Helvetica-regular.ttf")
As far as I can see, it is not possible to make this setting "global" by passing the path to this new .ttf file to the rc. If you are really desperate, you could try to extract all fonts from a .ttc into separate .ttf files, uninstall the .ttc and install the ttfs separately. To have the extracted font side-by-side with the original font from the .ttc, you need to change the font name with tools like FontForge. I haven't tested this, though.
Check if you are rendering the text with LaTeX, i.e., if text.usetex is set to True. Because LaTeX rendering only supports a few fonts, it largely ignores/overwrites your other fonts settings. This might be the cause.