I try to plot a frequency histogram with matplotlib but it doesn t work and i don t know where is the problem...
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
data = np.array([58.35, 71.83, 49.25, 38.89, 12.6, 58.34, 34.5, 11.6, 64.66, \
89.14, 101.84, 26.91, 38.74, 65.03, 35.23, 70.73, 54.52, 73.36, 74.35, \
60.54, 73.52, 24.58, 50.31, 55.63, 14.6, 53.64, 81.6])
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
n, bins, patches=ax.hist(data, 10, facecolor='green', alpha=0.75)
ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda y, pos: ('%.2f')%(y*1e-3)))
ax.set_ylabel('Frequency (000s)')
plt.show()
A part of the error message :
sh: 1: dvipng: not found
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1535, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 276, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 348, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "/usr/lib/pymodules/python2.7/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/pymodules/python2.7/matplotlib/figure.py", line 1034, in draw
func(*args)
...
In Ubuntu 14.04 I used this command to solve the problem:
sudo apt-get install dvipng
It looks like you are having a problem with the renderer or backend. You might want to try a different backend, by adding this at the beginning of your code:
import matplotlib as mpl
mpl.use('macOsX')
For other renderers, see here:
http://matplotlib.org/faq/usage_faq.html#what-is-a-backend
I found that if you have some Latex distr. installed you may also go with:
sudo tlmgr install dvipng
This is especially helpful for Mac, alternatively you can use ports:
sudo port install dvipng
For MacOS add this to your code!
import matplotlib as mpl
mpl.use('macOsX')
Related
I am having problems with basemap - arcgisimage function. Sample code below
...
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
from PIL import Image
m = Basemap(
llcrnrlat=40.361369, llcrnrlon=-80.0955278,
urcrnrlat=40.501368, urcrnrlon=-79.865723,
epsg = 2272
)
#m.arcgisimage(service='ESRI_StreetMap_World_2D'
, xpixels=7000, verbose=True)
m.arcgisimage(service='World_Physical_Map', xpixels=7000, ypixels=None, dpi=96,verbose=True)
#m.arcgisimage(service='ESRI_Imagery_World_2D', xpixels=7000, verbose=True)
plt.show()
...
when I run this the arcgisimage() function crashes in PIL with error message
Traceback (most recent call last):
File "C:\Machine Learning\Geospatial\pittsburgh_map.py", line 11, in <module>
m.arcgisimage(service='World_Physical_Map', xpixels=7000, ypixels=None, dpi=96,verbose=True)
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\mpl_toolkits\basemap\__init__.py", line 4263, in arcgisimage
return self.imshow(imread(urlopen(basemap_url)),ax=ax,
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\matplotlib\image.py", line 1490, in imread
with img_open(fname) as image:
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\ImageFile.py", line 121, in __init__
self._open()
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\PngImagePlugin.py", line 692, in _open
cid, pos, length = self.png.read()
File "C:\Users\peter\AppData\Local\Programs\Python\Python38\lib\site-packages\PIL\PngImagePlugin.py", line 162, in read
pos = self.fp.tell()
io.UnsupportedOperation: seek
I had the same problem, most probably you have installed it using conda. I deinstalled the basemap module and reinstalled it with pip. then everything worked normally
If you followed the basemap installation instructions, then any issues you have with running basemap will probably remain unfixed as it is is deprecated in favor of cartopy https://github.com/matplotlib/basemap.
I've got a simple code:
from matplotlib import pyplot as plt
plt.plot([1,2,5])
plt.show()
It works fine in jupyter notebook, however when I try to run it using command line:
$ python3 main.py
It throws an error:
_tkinter.TclError: unknown color name "[97]#282a36"
The whole trackeback:
Traceback (most recent call last):
File "main.py", line 2, in <module>
plt.plot([1,2,5])
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 2811, in plot
return gca().plot(
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 935, in gca
return gcf().gca(**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/pyplot.py", line 525, in figure
**kwargs)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backend_bases.py", line 3218, in new_figure_manager
return cls.new_figure_manager_given_figure(num, fig)
File "/home/user/.local/lib/python3.6/site-packages/matplotlib/backends/_backend_tk.py", line 1008, in new_figure_manager_given_figure
window = Tk.Tk(className="matplotlib")
File "/usr/lib/python3.6/tkinter/__init__.py", line 2023, in __init__
self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
_tkinter.TclError: unknown color name "[97]#282a36"
I already tried changing matplotlib's backend:
import matplotlib
matplotlib.use('pdf') # Or using other arguments matplotlib.use('Agg')
import matplotlib.pyplot as plt
plt.plot([1,2,5])
plt.show()
It gives me the same error message.
I also tried installing matplotlib using pip and my distribution package manager, both giving me the same error.
tkinter has been installed from my distribution repositories.
Any suggest would be helpful, I couldn't find any solution on similar questions.
After reading this issue on matplotlib's Github page, I emptied out my .Xresources and it fixed the issue.
So I looked a little bit more into the .Xresources file and I found out a line:
*background: [97]#282a36
Which was the cause of matplotlib complaining about a color nameed: [97]#282a36:
_tkinter.TclError: unknown color name "[97]#282a36"
Removing [97] from the line fixed the issue. remember that you have to run:
xrdb -merge .Xresources
To make the changes take place.
I get a latex error in matplotlib when running the following commands within python 2.7.15. It occurs when using a logarithmic axis scale. Whether the error appears or not depends on the matplotlib version, I tested with 1.5.1 (error does not occur) and 2.2.3 (error occurs). The error also only occurs when the code is executed within a single block (like in a function). See below for the minimal example (execute in two separate python consoles!). What exactly causes the error and how can I avoid it, while using the new matplotlib and tex mode?
Common code for both cases:
import sys
default_sys_path = sys.path
import numpy as np
def reproduce_error(old_matplotlib, outname):
if old_matplotlib == True:
sys.path = ['/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages'] + default_sys_path
else:
sys.path = ['/scratch/seismo/proxauf/conda/lib/python2.7/site-packages'] + default_sys_path
import matplotlib
import matplotlib.pyplot as plt
print matplotlib.__version__
print matplotlib.__path__
plt.rcParams['text.usetex'] = True
plt.semilogy(np.arange(1,10)*10**(-10))
plt.savefig('/home/proxauf/%s' % outname)
plt.close()
plt.rcParams['text.usetex'] = False
Case 1 code and output (matplotlib 1.5.1):
reproduce_error(old_matplotlib=True, outname='test_mathdefault_old.pdf')
1.5.1
['/opt/local/anaconda/anaconda-2.2.0/lib/python2.7/site-packages/matplotlib']
Case 2 code and output (matplotlib 2.2.3):
reproduce_error(old_matplotlib=False, outname='test_mathdefault_new.pdf')
2.2.3
['/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib']
Traceback (most recent call last):
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 519, in _draw_idle
self.draw()
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 437, in draw
self.figure.draw(self.renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/figure.py", line 1493, in draw
renderer, self, artists, self.suppressComposite)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/axes/_base.py", line 2635, in draw
mimage._draw_list_compositing_images(renderer, self, artists)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/axis.py", line 1192, in draw
renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/axis.py", line 1130, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/text.py", line 922, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/text.py", line 309, in _get_layout
ismath=ismath)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 236, in get_text_width_height_descent
s, fontsize, renderer=self)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/texmanager.py", line 501, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/texmanager.py", line 365, in make_dvi
texfile], tex)
File "/scratch/seismo/proxauf/conda/lib/python2.7/site-packages/matplotlib/texmanager.py", line 344, in _run_checked_subprocess
exc=exc.output.decode('utf-8')))
RuntimeError: latex was not able to process the following string:
'$\\\\mathdefault{10^{-10}}$'
Here is the full report generated by latex:
This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013/TeX Live for SUSE Linux)
restricted \write18 enabled.
entering extended mode
(/home/proxauf/.cache/matplotlib/tex.cache/be547c40948f52354492209662050ad0.tex
LaTeX2e <2011/06/27>
Babel <3.9f> and hyphenation patterns for 78 languages loaded.
(/usr/share/texmf/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texmf/tex/latex/base/size10.clo))
(/usr/share/texmf/tex/latex/type1cm/type1cm.sty)
(/usr/share/texmf/tex/latex/base/textcomp.sty
(/usr/share/texmf/tex/latex/base/ts1enc.def))
(/usr/share/texmf/tex/latex/geometry/geometry.sty
(/usr/share/texmf/tex/latex/graphics/keyval.sty)
(/usr/share/texmf/tex/generic/oberdiek/ifpdf.sty)
(/usr/share/texmf/tex/generic/oberdiek/ifvtex.sty)
(/usr/share/texmf/tex/generic/ifxetex/ifxetex.sty)
Package geometry Warning: Over-specification in `h'-direction.
`width' (5058.9pt) is ignored.
Package geometry Warning: Over-specification in `v'-direction.
`height' (5058.9pt) is ignored.
) (./be547c40948f52354492209662050ad0.aux)
(/usr/share/texmf/tex/latex/base/ts1cmr.fd)
*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Undefined control sequence.
<recently read> \mathdefault
l.13 ...000000}{12.500000}{\sffamily $\mathdefault
{10^{-10}}$}
No pages of output.
Transcript written on be547c40948f52354492209662050ad0.log.
From that I understand the error is because of command \mathdefault. It is a command defined in the python, and no is a base command of Latex. Thus, to solve this problem, you need put above of plt.semilogy(np.arange(1,10)*10**(-10)) the below commands:
from matplotlib import rcParams
rcParams['text.latex.preamble'] = r'\newcommand{\mathdefault}[1][]{}'
Thereby,the command \mathdefault will be defined and will do nothing.
I rewrote you code with those suggestions,
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['text.usetex'] = True
rcParams['text.latex.preamble'] = r'\newcommand{\mathdefault}[1][]{}'
plt.semilogy(np.arange(1,10)*10**(-10))
# plt.savefig('/home/proxauf/%s' % outname) ## outname????
plt.close()
rcParams['text.usetex'] = False
I am running my python script in another machine by using ssh command in linux. I have also run this command :
source ~/.bashrc
after logging in the other machine, in order to define the proper paths in the new machine. I was getting the error message for running the following python code lines even I have tried to follow the instruction in this question by defining the backend.
>>> import matplotlib
>>> import pylab as plt
>>> matplotlib.use('Agg')
>>> import numpy as np
>>> x=np.arange(0,2,0.001)
>>> y=np.sin(x)**2+4*np.cos(x)
>>> fig = plt.figure()
>>> plt.plot(x,y,'r.')
The error message
This probably means that Tcl wasn't installed properly.
Traceback (most recent call last):
File "Systematic_Optimised.py", line 513, in <module>
fig = plt.figure()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/pyplot.py", line 435, in figure
**kwargs)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 47, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 54, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4agg.py", line 72, in __init__
FigureCanvasQT.__init__(self, figure)
File "/vol/aibn84/data2/zahra/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/vol/anaconda/lib/python2.7/site-packages/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
any suggestion how to fix the problem
You must declare matplotlib.use('agg') before import pylab as plt.
Reference
Add
plt.switch_backend('agg')
after
import matplotlib.pyplot as plt
I am trying to run a python script using cron. The script runs without issue from the command line but has problems with matplotlib when run from cron. The error is below.
Traceback (most recent call last):
File "/home/ubuntu/python/spread.py", line 154, in <module>
plot_spread(lat, lon, vals, mean, maxs, mins, stdp, stdm, ens_members)
File "/home/ubuntu/python/spread.py", line 81, in plot_spread
plt.fill_between(x, maxs, stdp, color='r', alpha=0.2)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 2785, in fill_between
ax = gca()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 928, in gca
return gcf().gca(**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 578, in gcf
return figure()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/pyplot.py", line 527, in figure
**kwargs)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 46, in new_figure_manager
return new_figure_manager_given_figure(num, thisFig)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 53, in new_figure_manager_given_figure
canvas = FigureCanvasQTAgg(figure)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 76, in __init__
FigureCanvasQT.__init__(self, figure)
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4.py", line 68, in __init__
_create_qApp()
File "/usr/lib/python2.7/dist-packages/matplotlib-1.5.0_818.gfd83789-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt5.py", line 138, in _create_qApp
raise RuntimeError('Invalid DISPLAY variable')
RuntimeError: Invalid DISPLAY variable
I got a similar error when I tried to import matplotlib.pyplot in python using cron. You can force matplotlib to not use any Xwindows backend. Do this:
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
These links might be also helpful:
Generating a PNG with matplotlib when DISPLAY is undefined
Generating matplotlib graphs without a running X server
Hope this is helpful!