I'm trying to plot with seaborn.kdeplot with LaTeX labels. What I tried is the following:
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(font_scale=1.5, rc={'text.usetex' : True})
x = np.linspace(-50,50,100)
y = np.sin(x)**2/x
fig = plt.figure(1)
sns.set_style('white')
sns.kdeplot(np.array(y), label='hey')
fig.gca().set(xlabel=r'$e(t_0)$ [s]', ylabel='PDF')
fig.savefig("seaborntest.png", close = True, verbose = True)
Running this I've got the following error:
Traceback (most recent call last):
File "./sns_problem.py", line 17, in <module>
fig.savefig("seaborntest.png", close = True, verbose = True)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 1363, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 2093, in print_figure
**kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 491, in print_png
FigureCanvasAgg.draw(self)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 439, in draw
self.figure.draw(self.renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/figure.py", line 999, in draw
func(*args)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/axes.py", line 2086, in draw
a.draw(renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib64/python2.7/site-packages/matplotlib/axis.py", line 1050, in draw
renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/axis.py", line 999, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/text.py", line 752, in get_window_extent
bbox, info = self._get_layout(self._renderer)
File "/usr/lib64/python2.7/site-packages/matplotlib/text.py", line 304, in _get_layout
ismath=False)
File "/usr/lib64/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 196, in get_text_width_height_descent
texmanager = self.get_texmanager()
File "/usr/lib64/python2.7/site-packages/matplotlib/backend_bases.py", line 597, in get_texmanager
self._texmanager = TexManager()
File "/usr/lib64/python2.7/site-packages/matplotlib/texmanager.py", line 137, in __init__
ff = rcParams['font.family'].lower()
AttributeError: 'list' object has no attribute 'lower'
What could be the problem? The strange thing is that I got this error even if I remove the line adding the labels. What is the proper way of using LaTeX in seaborn plot labels?
If you do not have latex install on your machine, this could be causing errors.
For Linux users try installing Latex:
sudo apt update
sudo apt-get install texlive-latex-extra texlive-fonts-recommended dvipng cm-super
If in notebook, restart the Kernel, and then the font should display using Latex.
Related
I am testing a python code which produces some plots from a database results using matplotlib with LateX. The problem is that I am getting only one plot and it is not labeled. Below the error and the lines of code that generates the error(I can post the whole method if needed).Any hint?
if fileName is not None:
if verbose:
print("Saving file")
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages(fileName) as pdf:
for fig in figures:
for ax in fig.axes:
__add_legend(ax, outside=legend_outside)
pdf.savefig(fig)
return figures
__add_legend is given by the following
def __add_legend(ax, handles=None, labels=None, alpha=0.5,
outside=None, loc='best', *args, **kwargs):
if not handles:
handles, labels = ax.get_legend_handles_labels()
if not handles:
return
if outside is not None and len(handles) >= outside:
# Shrink current axis by 20%
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.legend(handles, labels, loc='center left', fancybox=False,
frameon=False, shadow=False,
bbox_to_anchor=(1, 0.5)).draggable(True)
else:
ax.legend(handles, labels, loc=loc, fancybox=True,
shadow=True).draggable(True)
The error message
Traceback (most recent call last):
File "../plot_prog.py", line 5, in <module>
run_program()
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1364, in run_program
else filteritr_convergent)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1285, in genPDFBooklet
pdf.savefig(fig)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends /backend_pdf.py", line 2473, in savefig
figure.savefig(self, format='pdf', **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1563, in savefig
self.canvas.print_figure(*args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backend_bases.py", line 2232, in print_figure
**kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 2536, in print_pdf
self.figure.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1159, in draw
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2319, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 1113, in draw
tick.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axis.py", line 254, in draw
self.label1.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 62, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/text.py", line 792, in draw
mtext=mtext)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 1912, in draw_tex
self._setup_textpos(curx, cury, angle, oldx, oldy)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 1770, in _setup_textpos
self.file.output(x - oldx, y - oldy, Op.textpos)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 589, in output
self.write(fill([pdfRepr(x) for x in data]))
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_pdf.py", line 149, in pdfRepr
raise ValueError("Can only output finite numbers in PDF")
ValueError: Can only output finite numbers in PDF
I used pdb command in python just before pdf.savefigs() and I obtained this
> /home/hammouc/Documents/mimclib-last/mimclib /plot.py(1287)genPDFBooklet()
-> pdf.savefig(fig)
(Pdb)
Traceback (most recent call last):
File "../plot_prog.py", line 5, in <module>
run_program()
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1367, in run_program
else filteritr_convergent)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1287, in genPDFBooklet
pdf.savefig(fig)
File "/home/hammouc/Documents/mimclib-last/mimclib/plot.py", line 1287, in genPDFBooklet
pdf.savefig(fig)
File "/usr/lib/python2.7/bdb.py", line 48, in trace_dispatch
return self.dispatch_line(frame)
File "/usr/lib/python2.7/bdb.py", line 67, in dispatch_line
if self.quitting: raise BdbQuit bdb.BdbQuit
I'm writing a lab report for uni and have decided to use pyplot to draw a graph for it. The units for one of my axes is V^(-1), but I can't seem to get matplotlib to write that with the power in superscript (it only superscripts the minus sign) when using the code:
plt.xlabel('$1/U (10^5 V ^-1 )$')
I'd also like to match the fonts used for the axes titles with that used for the values on the axes if at all possible. I've tried putting:
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
at the beginning of my code, but that gives me the error:
File "C:\Users\Sam\Documents\Uni\Labs\pytry.py", line 92, in <module>
plt.savefig("Xrayplot.png")
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\pyplot.py", line 561, in savefig
return fig.savefig(*args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.py", line 1421, in savefig
self.canvas.print_figure(*args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_wxagg.py", line 85, in print_figure
FigureCanvasAgg.print_figure(self, filename, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backend_bases.py", line 2220, in print_figure
**kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 505, in print_png
FigureCanvasAgg.draw(self)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 451, in draw
self.figure.draw(self.renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\figure.py", line 1034, in draw
func(*args)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axes.py", line 2086, in draw
a.draw(renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axis.py", line 1089, in draw
renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\axis.py", line 1038, in _get_tick_bboxes
extent = tick.label1.get_window_extent(renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\text.py", line 753, in get_window_extent
bbox, info, descent = self._get_layout(self._renderer)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\text.py", line 320, in _get_layout
ismath=False)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\backends\backend_agg.py", line 205, in get_text_width_height_descent
renderer=self)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\texmanager.py", line 666, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "C:\Users\Sam\AppData\Local\Enthought\Canopy\User\lib\site-packages\matplotlib\texmanager.py", line 413, in make_dvi
'LaTeX: \n\n' % repr(tex)) + report)
RuntimeError: LaTeX was not able to process the following string:
'lp'
Here is the full report generated by LaTeX:
Any help would be much appreciated.
For the superscript add { } around the text that should be super scripted. For the fonts i don't know the solution.
plt.xlabel('$1/U (10^5 V ^{-1} )$')
Just wanted to see if others thought that the following behaviour in matplotlib plot_date was buggy, or if it's just something I should put up with.
I have a multi-panel plot that I set up with sharex to facilitate zoom/pan on all axes, and I plot time series data in both panels. However, in the second panel, all of the data happens to be invalid (in this example I mask it).
from matplotlib.pyplot import figure,show
from datetime import datetime,timedelta
from numpy import sin,cos,linspace,pi,ma,array
fig=figure(figsize=(16,9))
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212,sharex=ax1)
# xdata is seconds
xdata=linspace(0,9999,10000)
tdata=array([datetime(2000,1,1)+timedelta(seconds=ss) for ss in xdata])
data1=ma.masked_array(sin(pi*xdata/300),mask=False)
data2=ma.masked_array(cos(pi*xdata/300),mask=True)
ax1.plot_date(tdata,data1,marker='',color='r')
ax2.plot_date(tdata,data2,marker='',color='b')
show()
I'd expect (prefer) it to just show up a blank panel, not to fail and give me a long unhelpful traceback. Is this the expected behaviour?
Notes:
This script also fails if I use ax.plot(...) instead of ax.plot_date(...)
It works fine (i.e. gives me an empty panel) if I just plot against xdata, not the datetime array tsdata (but I have to use ax1.set_xlim(xdata[0],xdata[-1]) to get a sensible domain displayed):
ax1.plot(xdata,data1,marker='',color='r')
ax2.plot(xdata,data2,marker='',color='b')
ax1.set_xlim(xdata[0],xdata[-1])
show()
I have just realised I can rescue the above plot by forcing the ax2 limits right before the show() command. I still think that the failure in the main example is inelegant:
ax2.set_xlim(tdata[0],tdata[-1])
show()
What do the experts think?
Thanks!
F.Y.I., This was on matplotlib 1.1.0, compiled from source on my PC.
Here is the traceback that I get:
Traceback (most recent call last):
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backendsbackend_gtk.py", line 395, in expose_even
self._render_figure(self._pixmap, w, h)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_gtkagg.py", line 75, in _render_f
FigureCanvasAgg.draw(self)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 401, in draw
self.figure.draw(self.renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/figure.py", line 884, in draw
func(*args)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axes.py", line 1983, in draw
a.draw(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 1036, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 926, in _update_ticks
tick_tups = [ t for t in self.iter_ticks()]
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/axis.py", line 873, in iter_ticks
majorLocs = self.major.locator()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 749, in __call__
self.refresh()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 758, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 530, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 289, in num2date
if not cbook.iterable(x): return _from_ordinalf(x, tz)
File "/home/tchubb/local/lib/python2.7/site-packages/matplotlib/dates.py", line 203, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
If you suspect this is an IPython bug, please report it at:
https://github.com/ipython/ipython/issues
or send an email to the mailing list at ipython-dev#scipy.org
Yes, I would call this a bug, or at least an oversight which looks like it has been fixed (via #ali_m https://github.com/matplotlib/matplotlib/issues/162).
I was getting this exception, but that was on a version of 1.3.x from June (my bad, thought I had a more current version on this computer). Current master does not have this problem and #ali_m reports that it also works on 1.2.1 and 1.3.0 so I suspect the fix is to upgrade you version of matplotlib.
What looks like is going on is that there isn't a check in the code that sorts out where to put the ticks has no check to make sure you have given in non-empty data.
The reason that setting the limits explicitly prevents the error is that the code never tries to figure out what the range of your empty data is.
Please create a github issue for this (and include the trace back in the issue).
In [7]: Traceback (most recent call last):
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4.py", line 366, in idle_draw
self.draw()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_qt4agg.py", line 148, in draw
FigureCanvasAgg.draw(self)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/backends/backend_agg.py", line 440, in draw
self.figure.draw(self.renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/figure.py", line 1027, in draw
func(*args)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axes.py", line 2088, in draw
a.draw(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/artist.py", line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 1076, in draw
ticks_to_draw = self._update_ticks(renderer)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 938, in _update_ticks
tick_tups = [t for t in self.iter_ticks()]
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/axis.py", line 882, in iter_ticks
majorLocs = self.major.locator()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 785, in __call__
self.refresh()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 794, in refresh
dmin, dmax = self.viewlim_to_dt()
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 560, in viewlim_to_dt
return num2date(vmin, self.tz), num2date(vmax, self.tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 305, in num2date
return _from_ordinalf(x, tz)
File "/home/tcaswell/local_installs/lib/python2.7/site-packages/matplotlib-1.3.x-py2.7-linux-x86_64.egg/matplotlib/dates.py", line 208, in _from_ordinalf
dt = datetime.datetime.fromordinal(ix)
ValueError: ordinal must be >= 1
I'm trying to use pylab and networkx to draw a directed-graph.
Below is a small demo script and the error it produces (and, the window created by pylab is empty).
Googling shows that this error was supposed to be fixed in mathplotlib's svn already in 2008.
Anyone could point me in the right direction?
This script:
import pylab
import networkx as nx
def Working_with_graphs_using_networkx():
fig = pylab.figure()
g = nx.Graph(name = "graph")
pylab.title(g.name)
g.add_node("John")
g.add_node("Maria")
g.add_edge("John", "Maria")
pos = nx.spring_layout(g)
nx.draw(g, pos)
if __name__ == "__main__":
Working_with_graphs_using_networkx()
pylab.show()
Produces this error (on Python 2.6 under cygwin):
$ python demo_SeqBase.py
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1410, in __call__
return self.func(*args)
File "/usr/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py", line 236, in resize
self.show()
File "/usr/lib/python2.6/site-packages/matplotlib/backends/backend_tkagg.py", line 239, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/python2.6/site-packages/matplotlib/backends/backend_agg.py", line 401, in draw
self.figure.draw(self.renderer)
File "/usr/lib/python2.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/matplotlib/figure.py", line 884, in draw
func(*args)
File "/usr/lib/python2.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/matplotlib/axes.py", line 1983, in draw
a.draw(renderer)
File "/usr/lib/python2.6/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/lib/python2.6/site-packages/matplotlib/collections.py", line 238, in draw
self._linewidths, self._linestyles, self._antialiaseds, self._urls)
File "/usr/lib/python2.6/site-packages/matplotlib/backends/backend_agg.py", line 84, in draw_path_collection
return self._renderer.draw_path_collection(*kl, **kw)
IndexError: Unexpected SeqBase<T> length.
I'm trying to set tick mark positions in matplotlib. I get errors when running the following minimal example:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
x = 10.*np.random.randn(1000)
y = 10.*np.random.randn(1000)
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
ax.scatter(x, y)
ax.xaxis.set_major_formatter(MultipleLocator(1.))
ax.yaxis.set_major_formatter(MultipleLocator(1.))
plt.show()
The error lies with the two lines that set the x- and y-axis tick marks. If I use NullFormatter() instead, or omit these lines entirely, the code runs fine and produces the expected plot. The above code, however, returns the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1413, in __call__
return self.func(*args)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 245, in resize
self.show()
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_tkagg.py", line 248, in draw
FigureCanvasAgg.draw(self)
File "/usr/lib/pymodules/python2.7/matplotlib/backends/backend_agg.py", line 394, 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 798, in draw
func(*args)
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/axes.py", line 1946, in draw
a.draw(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/axis.py", line 971, in draw
tick_tups = [ t for t in self.iter_ticks()]
File "/usr/lib/pymodules/python2.7/matplotlib/axis.py", line 906, in iter_ticks
self.major.formatter.set_locs(majorLocs)
AttributeError: MultipleLocator instance has no attribute 'set_locs'
I've tried googling this error, but I can't find anyone else who has a similar problem. Any ideas as to why the use of locators is yielding errors?
MultipleLocator is a locator, not a formatter. You want to use
ax.xaxis.set_major_locator(MultipleLocator(1.))
ax.yaxis.set_major_locator(MultipleLocator(1.))
This works for me (doesn't look too pretty using 1, but it works).