matplotlib pgf pdfcomment preamble causing blank extra page - python

I am trying to add some tooltips to a matplotlib pdf file. To do this I am using pgf so I can add "pdfcomment" in the preamble. However, when I add pdfcomment to the preamble I get a blank extra page. This does not happen with other packages like xcolor and hyperref (for example).
Here is the code as I'm using it for testing, which I got from this discussion:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use("pgf")
pgf_with_pdflatex = {
"pgf.texsystem": "pdflatex",
"pgf.preamble": r"\usepackage{pdfcomment}",
}
mpl.rcParams.update(pgf_with_pdflatex)
fig = plt.figure(figsize=(4.5,2.5))
for i in range(5):
plt.text(i,i,r"\pdftooltip{\rule{0.3cm}{0.3cm}}{(%d,%d)}" % (i,i))
plt.plot(range(5), linewidth = 10)
plt.savefig("tooltips.pdf")
plt.close()
Which works, except that it makes an extra page. Below is a minimalist version which reproduces the problem.
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use("pgf")
mpl.rcParams["pgf.texsystem"] = "pdflatex"
#mpl.rcParams["pgf.preamble"] = r"\usepackage{pdfcomment}" # uncomment to get blank page
plt.plot(range(5), linewidth = 10)
plt.savefig("tooltips.pdf")
plt.close()
Essentially if you uncomment that one line you will get an extra blank page as output which I don't want. Below are two example screenshots that I get, one with the extra page and one without (all I changed was uncommenting the line).
As extra information, my pdflatex version is:
pdfTeX 3.14159265-2.6-1.40.20 (TeX Live 2019/Debian)
python3 version is:
Python 3.8.10
Matplotlib version is:
3.3.2
Please help and please be kind, this is my first time posting a question.
Edit: as requested here is the intermediate LaTeX file. This is in the form of a pgf file which one would include in a tex document I think. I wasn't sure how to get the .tex directly.

It isn't pretty, but I think I found a work around. Here is the modified minimal version which only outputs a single page. Based on the comment by samcarter_is_at_topanswers.xyz, the problem is with matplotlib not LaTeX, so I just include a pdflatex call in the script. Here is the minimal working version:
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.use("pgf")
mpl.rcParams["pgf.texsystem"] = "pdflatex"
mpl.rcParams["pgf.preamble"] = r"\usepackage{pdfcomment}"
plt.plot(range(5), linewidth = 10, zorder = 10)
plt.savefig("tooltips.pgf")
plt.close()
import subprocess
with open("tooltips.tex", "w") as f:
f.write(r"""
\documentclass{standalone}
\usepackage{pgf}
\usepackage{pdfcomment}
\begin{document}
\input{tooltips.pgf}
\end{document}
""")
subprocess.run(["pdflatex", "tooltips.tex"])
Note that matplotlib outputs a .pgf file instead of a .pdf file.

Related

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)

Printing image in r-markdown using matplotlib and python code

I am trying to run the python code using the R-Markdown file (RMarkdown to pdf).
What I achieved till now -
1- I am able to configure my python engine using knitr and reticulate library
2- I am able to execute my python codes.
What I tried -
1- I tried all the methods which are discussed in this forum, but nothing is working out.
2- I also tried to save the image,(as one of the posts here suggests), but that also is not working.
My problem -
1- When I am trying to plot a graph using matlplotlib and command plt.imshow() and plt.show(), it's not printing the image in the output. Rather it's showing the image in a separate window. You can see my results in the attached image.
Result_of_my_code
Here is my code
```{r setup, include=FALSE}
library(knitr)
library(reticulate)
knitr::knit_engines$set(python = reticulate::eng_python)
```
```{python}
import numpy as np
import os
import torch
import torchvision.datasets as dsets
import matplotlib.pyplot as plt
print(os.getcwd())
os.chdir('D:\\1st year\\Python codes\\CIFR Analysis\\self contained analysis')
print(os.getcwd())
train_mnist = dsets.MNIST("../data", train=True)
test_mnist = dsets.MNIST("../data", train= False)
print(len(train_mnist))
#print(train_mnist[0][0])
plt.imshow(train_mnist[0][0], cmap="gray")
#plt.savefig("trainzero.png")
plt.show()
```
Kindly, help me to fix this issue, as I want to compile my python codes using the R markdown file.
thanks
So with R Markdown, you have to do some things a little differently. In the following, I have a dataframe with two series created by concatenating them. The original plotting code in the Jupyter Notebook is as follows and just printed out the series.
# make a plot of model fit
train.plot(figsize=(16,8), legend=True)
backtest.plot(legend=True);
However, it does not work with way with R Markdown. Then with plotting, you always have to assign them, and with the code below, you get the same plot.
dfreg = pd.concat([reg, backtest], axis = 1)
ax = dfreg.plot(figsize=(16,8), legend = True)
ax1 = predictions.plot(legend=True)
plt.show()
This is common with other plotting functions like plot_acf() too.

How to use pgf backend to include hyperlink in matplotlib pdf plot?

I wish to include a hyperlink in a matplotlib plot, which I can output as a pdf (to later be inserted into a LaTeX document).
I know this kind of question has been asked, but the solutions which I've seen only seem to give rise to some error. I'm currently attempting to use the pgf backend, and my code is as below:
import matplotlib
matplotlib.use('pgf')
import matplotlib.pyplot as plt
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
matplotlib.rcParams['pgf.preamble'] = [r'\usepackage{hyperref}', ]
x = (1,2,3,4)
y = (1,4,9,16)
plt.figure()
plt.plot(x,y,'bo')
plt.title(r"\href{http://www.google.com}{Test Link}",color='blue')
plt.savefig('Test.pdf')
plt.close()
However, I keep getting the following error:
matplotlib.backends.backend_pgf.LatexError:
LaTeX returned an error, probably missing font or error in preamble
Not sure why this is, any help would be greatly appreciated.

Matplotlib 'eps' export using savefig generates error when using TeX in figure

I am trying to export a figure which is rendered using TeX. I use the following minimal example code to accomplish this:
import matplotlib.pyplot as plt
from matplotlib import rc
rc('text', usetex=True)
fig, ax = plt.subplots()
fig.savefig('plot.eps', format='eps')
This generates an error:
RuntimeError: ghostscript was not able to process your image.
Here is the full report generated by ghostscript:
(it doesn't actually provide the full report)
Now if i render without TeX then everything works fine:
rc('text', usetex=False)
Also rendering with TeX and outputting to PNG or PDF works fine aswell.
Anyone know what is going on?

Imshow doesn't display image when used with astropy

I am running into a problem viewing images with astropy. Here is my code:
from astropy.io import fits
import matplotlib.pyplot as plt
hdu_list=fits.open("500m2deep.fit")
image_data=hdu_list[0].data
hdu_list.close()
plt.imshow(image_data,cmap='gray')
plt.show()
Opening the file works fine, I can display the entries of image_data and alike. But the picture doesn't show if I use imshow. It displays the following error:
C:\Python27\lib\site-packages\IPython\core\formatters.py:239: FormatterWarning: Exception in image/png formatter:
FormatterWarning,
If I use, as suggested on some sites, %matplotlib inline, or something similar, this error disappears, but no image shows at all, the program runs, terminates, no picture pops up. I also tried adding something like plt.figure() before imshow() but that doesn't help either.
This happens if I use Spyder, Ipython, or Ipython Notebook. I am using the newest version of python(x,y) for all of this.
How can I display the pictures?
Maybe too late to be a useful solution for you, but mayb someone else can profit.
I recently ran into the same issue on Ubuntu 16.04, python 3.5 and Astropy 1.1.1 using the sample code from the astropy website (first and last line added by me), which is:
#!/usr/bin/python3
import matplotlib.pyplot as plt
from astropy.wcs import WCS
from astropy.io import fits
from astropy.utils.data import get_pkg_data_filename
filename = get_pkg_data_filename('galactic_center/gc_msx_e.fits')
hdu = fits.open(filename)[0]
wcs = WCS(hdu.header)
plt.subplot(projection=wcs)
plt.imshow(hdu.data, vmin=-2.e-5, vmax=2.e-4, origin='lower')
plt.grid(color='white', ls='solid')
plt.xlabel('Galactic Longitude')
plt.ylabel('Galactic Latitude')
plt.show()
It did open the figure window, but did not display any image data.
Updating the astropy version to 1.3 (which also updated numpy to 1.11.3) fixed the issue. Now it works fine.

Categories