Imshow doesn't display image when used with astropy - python

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.

Related

matplotlib pgf pdfcomment preamble causing blank extra page

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.

How do you log stretch a FITS image and change its contrast?

I'm trying to use astropy 2.0.11 with python 2.7.15 to edit a fits image by applying a log stretch to it and change the contrast, and I have't been able to figure it out.
I've been trying to follow the tutorials on the astropy website for opening and manipulating fits files, but I'm wondering if the tutorials will only work for the latest version of astropy and on python 3?
Sorry about the organization of my code. This is prototype code and I'm just trying to test a few things and get this to work.
import time
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm
import astropy.visualization
from astropy.io import fits
from astropy.utils.data import download_file
from astropy.visualization import astropy_mpl_style
plt.style.use(astropy_mpl_style)
from astropy.utils.data import get_pkg_data_filename
def main():
#My own fits file
#fitsImage = get_pkg_data_filename("C:\\20180807T000456.fits")
fitsImage = download_file('http://data.astropy.org/tutorials/FITS-images/HorseHead.fits', cache=True )
hdu_list = fits.open(fitsImage)
hdu_list.info()
#norm = ImageNormalize(stretch=LogStretch())
image_data = fits.getdata(fitsImage)
print(type(image_data))
print(image_data.shape)
hdu_list.close()
plt.figure()
plt.imshow(image_data, cmap='gray', norm=LogNorm())
plt.colorbar()
# I chose the tick marks based on the histogram above
cbar = plt.colorbar(ticks=[5.e3,1.e4,2.e4])
cbar.ax.set_yticklabels(['5,000','10,000','20,000'])
time.sleep(10)
I am also unable to get the image to display with the plt.imshow()
Any insight would be helpful
You're so close! I ran your code in Python 2.7 and all you need to do is add
plt.show()
before time.sleep(10) (any reason you're including this?) and you get
Also, I don't think you need to include the colorbar and yticklabels, plt.imshow automatically adds the colorbar with the lognorm scale (I commented that section out when I got the image).

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.

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?

Image does not show with matplotlib.pyplot with ipython or python

If I do the following commands in iPython or just Python,
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
img=mpimg.imread('stinkbug.png')
imgplot = plt.imshow(img)
then nothing happens (no image appear anywhere).
But if I do the following commands:
import scipy.misc as misc
img=misc.imread('stinkbug.png')
misc.imshow(img)
then image appears inside separate window of ImageMagick.
Also, I can run ipython with qtconsole and will see image with first code.
What are the difference between two different ways of diplaying images? Can they be unified, i.e. work in similar way in both consoles? Is it possible to make first code work in normal ipython/python?
Add plt.show(imgplot) at the end of your code.
One line is missing to show the plot window:
plt.show()

Categories