matplotlib mathtext slanted fractions - python

Is it possible with matplotlib to create a slanted fractions ( /sfrac{1}{1} in Latex)
I tried r'$/sfrac{1}{2}$', but I get nothing...

You will have to use real LaTeX as follows:
import matplotlib
import matplotlib.pyplot as plt
# Use LaTeX for rendering
matplotlib.rcParams["text.usetex"] = True
# load the xfrac package
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage{xfrac}')
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([0,1],[1,0])
ax.text(.5, .5, r'$\sfrac{1}{2}$')
This creates:
You need to have a working LaTeX in your system plus of course the LaTeX xfrac package.

Related

Y-axis scientific notation formatter lost when convert matplotlib figure into html with mpld3

I am trying to convert a figure created with matplotlib into html to embed it into a web page with mpld3.fig_to_html method. For some reasons, the scientific notation is lost on the y-axis. If I try to save a local .png image the scientific notation is shown correctly.
Moreover if I save a local .html file with mpld3.save_html the scientific notation is lost as well.
Any idea ?
Here's an example:
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import mpld3
from matplotlib import ticker
t = [130940239,30492094,20394029]
s = [3898298328,3498328998234,39482]
fig, ax = plt.subplots()
formatter1 = ticker.ScalarFormatter(useMathText=True)
formatter1.set_scientific(True)
formatter1.set_powerlimits((0, 0))
ax.yaxis.set_major_formatter(formatter1)
ax.plot(t, s)
html_str = mpld3.fig_to_html(fig)
ax.grid()
mpld3.save_html(fig,"test_dummy.html")
fig.savefig("test.png")

Getting semi-transparent text with matplotlib+pgf backend when compiling in LateX

So I am using the pgf backendin matplotlib to include some automatically compiled references to some other parts of my Tex documents (figures, bibliography) in my TeX document.
import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
plt.figure()
plt.txt(0.0,0.5,r'Some text compiled in latex \cite{my_bib_tag}')
plt.savefig("myfig.pgf", bbox_inches="tight", pad_inches=0)
Then in my tex document I have the lines:
\usepackage[dvipsnames]{xcolor}
%yada yada yada
\begin{figure}
\input{myfig.pgf}
\end{figure}
It is working great but when I try to add some transparency to the text it doesn't work. For instance when setting:
plt.txt(0.0,0.5,r'Some text compiled in latex \cite{my_bib_tag}', alpha=0.5)
The text appears unchanged, and if I try to do it in the compilation by using \textcolorfrom the xcolor package (or any other commands in LateX, like the transparent package) I get parsing errors when compiling the Python.
I tried escaping characters but somehow I cannot make it work.
plt.txt(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_bib_tag}}', alpha=0.5)
#raise ValueError !Undefined Control Sequence
EDIT 1: I tried adding the required package in the preamble, but it does not work when saving to pgf (with the pgf backend), it works using the Agg backend (I think it is expected behavior). But I need to save it in pgf to have the dynamic parsing of references.
import matplotlib
import matplotlib.pyplot as plt
matplotlib.rcParams["text.usetex"] = True
matplotlib.rcParams["text.latex.preamble"].append(r'\usepackage[dvipsnames]{xcolor}')
matplotlib.verbose.level = 'debug-annoying'
plt.figure()
plt.text(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_bib_tag}}', alpha=0.5)
#works in .png, does not work in .pgf
#plt.savefig("myfig.png", bbox_inches="tight", pad_inches=0)
EDIT 2: A work around is to use the color param in plt.text but what if I would like to use more complicated LateX styling...
Thanks to #ImportanceOfBeingErnest I finally made it work with the pgf backend:
import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
pgf_with_custom_preamble = {
"text.usetex": True, # use inline math for ticks
"pgf.rcfonts": False, # don't setup fonts from rc parameters
"pgf.preamble": [
"\\usepackage[dvipsnames]{xcolor}", # load additional packages
]
}
matplotlib.rcParams.update(pgf_with_custom_preamble)
plt.figure()
plt.text(0.0,0.5,r'\textcolor{gray}{Some text compiled in latex \cite{my_biblio_tag}}')
plt.savefig("myfig.pgf", bbox_inches="tight", pad_inches=0)

Latex colors not rendered in matplotlib text

Tex's \textcolor seems to be ignored in my plottling script
import matplotlib as matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'text.usetex': True})
matplotlib.rc(
'text.latex', preamble=r"\usepackage{xcolor}")
fig, ax = plt.subplots()
ax.set_ylabel(r'\textcolor{red}{aaaaaaa}')
plt.show()
does not give me a red text, it produces:
Am I missing something?
It's explained in more detail here : https://matplotlib.org/users/usetex.html but seems like it only works when you export it to a ps file. For me, it works in color if you're saving it as a ps file while the same file inline doesn't work.
Slight workaround here.
import matplotlib as matplotlib
from matplotlib import pyplot as plt
matplotlib.rcParams.update({'text.usetex': True})
matplotlib.rc('text.latex', preamble=r"\usepackage{xcolor}")
fig, ax = plt.subplots()
ax.set_ylabel(r"aaaaaaa", color='r')
#plt.savefig(r"foo.ps")
# you can include the above line if you're using your old code.
plt.show()

Scientific Notation in matplotlib inline plots in jupyter

I am plotting values that are of order 10^-8 and I would like my inline plot in jupyter to output the yaxis ticks in that (scientific) notation. I tried :
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%.1E'))
as well as
plt.gca().yaxis.get_major_formatter().set_powerlimits((0, -10))
and
plt.ticklabel_format(style='sci')
but nothing seems to work. What am I doing wrong? I have the following example:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import mpld3
mpld3.enable_notebook()
import matplotlib.ticker as mtick
a=5*10**-8
b=3*10**-8
x=np.arange(0,10,0.01)
y=a*x+b
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
plt.plot(x,y)
# plt.ticklabel_format(style='sci')
# plt.gca().yaxis.get_major_formatter().set_powerlimits((0, -10))
plt.gca().yaxis.set_major_formatter(mtick.FormatStrFormatter('%.0e'))
plt.show()
Any pointers would be helpful as I don't find anything on this, besides ticks format of an axis in matplotlib, enter link description here or Change x axes scale in matplotlib
NOTE: If I comment out the lines with import mpld3 and mpld3.enable_notebook() then it works but cannot interact with the plot... Is there some special treatment of matplotlib when plotting inline in jupyter?
Thanks!
You can use set_yticklabels to have a similar looking output.
ax = plt.gca()
ax.set_yticklabels(['10^-8','2*10^-8','3*10^-8','4*10^-8'])

Non-italicized tick labels with pgf in matplotlib

I am using the pgf backend in matplotlib 1.5.3 to produce publication-quality figures. Here is how I set up the plotting script.
import matplotlib as mpl
mpl.use('pgf')
pgf_with_latex = { # setup matplotlib to use latex for output
"pgf.texsystem": "pdflatex", # change this if using xetex or lautex
"text.usetex": True, # use LaTeX to write all text
"font.family": "sans-serif",
"font.sans-serif": "Bitstream Vera Sans, Helvetica, Computer Modern Sans Serif",
"pgf.preamble": [
r"\usepackage[utf8x]{inputenc}", # use utf8 fonts because your computer can handle it :)
r"\usepackage[T1]{fontenc}", # plots will be generated using this preamble
r"\usepackage{textcomp}",
r"\usepackage{sfmath}", # sets math in sans-serif
]
}
mpl.rcParams.update(pgf_with_latex)
import matplotlib.pyplot as plt
def newfig():
plt.clf()
fig = plt.figure(figsize=(4, 2))
ax = fig.add_subplot(111)
return fig, ax
fig, ax = newfig()
ax.set_xlabel("Some x-label text")
plt.gcf().tight_layout()
plt.savefig(os.getcwd() + "/test.pdf")
plt.savefig(os.getcwd() + "/test.eps")
I am using the package sfmath to set all math environments in sans-serif. At the end I save in .pdf and .eps format. Here's the problem: While the pdfclearly uses sans-serif font everywhere, the eps file uses serif for all tick labels (not axis labels)! When I modify my LaTeX template to use sfmath it does not change the tick labels.
How can I prevent the epsfrom using serif font in the tick labels?
Edit: After a good day of experimenting, the only (barely) satisfying solution I found was to use .tiff as format, since this is also allowed by the journal. eps just seems to have problems and always turns out different than the pdf or other image formats.

Categories