ValueError in matplotlib when using \: LaTeX horizontal spacing - python

See MWE below:
import matplotlib.pyplot as plt
import matplotlib.offsetbox as offsetbox
fig = plt.figure()
ax = fig.add_subplot(111)
text1 = r'$a\,=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text2 = r'$a\;=\,{}\pm{}$'.format(0.01, 0.002) # Works.
text3 = r'$a\:=\,{}\pm{}$'.format(0.01, 0.002) # Does not work.
text = text3
ob = offsetbox.AnchoredText(text, pad=1, loc=6, prop=dict(size=13))
ob.patch.set(alpha=0.85)
ax.add_artist(ob)
plt.show()
While text1 and text2 which use \, and \; spacing will work without issues, text3 which uses \: (ie: the horizontal spacing located between the previous two) fails with a ValueError:
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 42, in on_draw_event
self._render_figure(w, h)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_gtk3agg.py", line 32, in _render_figure
backend_agg.FigureCanvasAgg.draw(self)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 469, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/figure.py", line 1085, in draw
func(*args)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/artist.py", line 59, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 2110, in draw
a.draw(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1107, in draw
bbox = self.get_window_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1063, in get_window_extent
w, h, xd, yd = self.get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 1014, in get_extent
w, h, xd, yd = self.get_child().get_extent(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/offsetbox.py", line 782, in get_extent
bbox, info, d = self._text._get_layout(renderer)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/text.py", line 320, in _get_layout
ismath=ismath)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/backends/backend_agg.py", line 228, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 3005, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/mathtext.py", line 2339, in parse
six.text_type(err)]))
ValueError:
a\:=\,0.01\pm0.002
^
Unknown symbol: \ (at char 1), (line:1, col:2)
Why is this LaTeX spacing not recognized?

Because matplotlib uses mathtext as default math renderer. Mathtext is a subset of regular TeX. You can use full LaTeX with:
from matplotlib import pyplot as plt
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = [r'\usepackage{amsmath}'] #if needed
plt.plot([1,2,3])
plt.title(r"$a\:=\,{}\pm{}$".format(0.01, 0.002))
plt.show()

Related

an error in python plot

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.linear_model import LinearRegression
a = np.zeros((1000,3))
fig=plt.figure()
ax=fig.gca(projection='3d')
line1,=ax.plot(a[:,0], a[:,1], a[:,2], 'k')
ax.set_xlabel('$x_1_t$');ax.set_ylabel('$x_1_t-tau$');ax.set_zlabel('$x_1_t-2tau$')
plt.title('hello')
plt.show()
I use python2.x. The error message is the following. Anyone knows how to fix it?
Traceback (most recent call last):
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_macosx.py", line 83, in _draw
self.figure.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py", line 1475, in draw
renderer, self, artists, self.suppressComposite)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/image.py", line 141, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axes3d.py", line 298, in draw
ax.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/mpl_toolkits/mplot3d/axis3d.py", line 306, in draw
self.label.draw(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py", line 55, in draw_wrapper
return draw(artist, renderer, *args, **kwargs)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/text.py", line 706, in draw
bbox, info, descent = textobj._get_layout(renderer)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/text.py", line 309, in _get_layout
ismath=ismath)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/backends/backend_agg.py", line 237, in get_text_width_height_descent
self.mathtext_parser.parse(s, self.dpi, prop)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mathtext.py", line 3293, in parse
box = self._parser.parse(s, font_output, fontsize, dpi)
File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/mathtext.py", line 2521, in parse
six.text_type(err)]))
ValueError:
^ Double subscript (at char 0), (line:1, col:1)
As the other answer suggests, the problem is trying to use double subscripts in the axis labels. The solution depends on how you would like the labels to look.
If you would like the 1 and the t to both be subscripts then you can use:
$x_{1t}$
If you want the first underscore to be an actual underscore then you can use
$x\_1_t$
The problem is in your labels, you are using a double subscripts:
$x_1_t$
If you change to just using single subscripts it should work (e.g):
$x_1t$

Using matplotlib scatter markers in text of legend together with Latex

I have a plot with an inset. The latter has a legend, in whose text I would like to use matplotlib scatter markers. I also want to be able to use LaTeX at the same time for all the labels and legends. The reason I am mentioning this is because I had a look at this thread and the solutions there don't work for me. I will explain why bellow.
Here is an example code (sorry for the functions I am plotting, couldn't think of anything)
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid.inset_locator import (inset_axes, InsetPosition, mark_inset)
from matplotlib import rc
rc('text', usetex=True)
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
fig, ax1 = plt.subplots()
ax1.scatter(x, np.cos(x), color = 'blue', marker = "D", s=47.5, label = r'$\cos$')
ax1.scatter(y, np.sin(y), color = 'cyan', marker = "*", alpha = 0.85, label = r'$\sin$')
ax1box = ax1.get_position()
x_value = -0.13
y_value = 0.675
legend=ax1.legend(loc = (ax1box.x0 + x_value, ax1box.y0 + y_value), handletextpad=0.1, prop={'size':8})
frame = legend.get_frame()
frame.set_alpha(0)
frame.set_linewidth(0)
ax2 = plt.axes([0.5,0.5,0.5,0.5])
ip = InsetPosition(ax1, [0.55,0,0.45,0.40])
ax2.set_axes_locator(ip)
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = r'Insert blue square marker here')
ax2.scatter(y, np.log(y)+1, color = 'brown', marker = "4", s=15, label = r'Insert cyan star marker here')
ax2.xaxis.tick_top()
ax2.xaxis.set_label_position('top')
ax2.yaxis.tick_right()
legend2=ax2.legend(loc = 'lower right', handletextpad=0.1, prop={'size':7})
frame2 = legend2.get_frame()
frame2.set_alpha(0)
frame2.set_linewidth(0)
plt.show()
If I am to go with the advice in here about LaTeX and try with
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = r'$\square$')
the plot shows with no legend in the inset.
If, instead, I decide to implement the unicode solution
ax2.scatter(x, np.tan(x), color = 'gray', marker = "v", s=15, label = '●')
I get the following error
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.5/tkinter/__init__.py", line 1562, in __call__
return self.func(*args)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 280, in resize
self.show()
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_tkagg.py", line 351, in draw
FigureCanvasAgg.draw(self)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 464, in draw
self.figure.draw(self.renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/figure.py", line 1144, in draw
renderer, self, dsu, self.suppressComposite)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/axes/_base.py", line 2426, in draw
mimage._draw_list_compositing_images(renderer, self, dsu)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/image.py", line 139, in _draw_list_compositing_images
a.draw(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/artist.py", line 63, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/legend.py", line 471, in draw
bbox = self._legend_box.get_window_extent(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 269, in get_window_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 391, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 262, in get_extent
w, h, xd, yd, offsets = self.get_extent_offsets(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in get_extent_offsets
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 462, in <listcomp>
for c in self.get_visible_children()]
File "/usr/local/lib/python3.5/dist-packages/matplotlib/offsetbox.py", line 835, in get_extent
bbox, info, d = self._text._get_layout(renderer)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/text.py", line 362, in _get_layout
ismath=ismath)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/backends/backend_agg.py", line 230, in get_text_width_height_descent
renderer=self)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 676, in get_text_width_height_descent
dvifile = self.make_dvi(tex, fontsize)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 399, in make_dvi
texfile = self.make_tex(tex, fontsize)
File "/usr/local/lib/python3.5/dist-packages/matplotlib/texmanager.py", line 314, in make_tex
fh.write(s.encode('ascii'))
UnicodeEncodeError: 'ascii' codec can't encode character '\u25cf' in position 226: ordinal not in range(128)
Which seems to come from the fact that I am using LaTeX, as If I comment out
# from matplotlib import rc
# rc('text', usetex=True)
Then I get everything working, but without LaTeX. (Well the circle I get is black, I haven't looked into whether it is possible to change its colour yet). I do want LaTeX, though, so this is not good for me.
As The Great, Big List of LaTeX Symbols tells us, \square is an AMS symbol. So, in order to use it you have to put \usepackage{amssymb} in your preamble, which can be done with
rc('text', usetex=True)
rc('text.latex', preamble=r'\usepackage{amssymb}')

Axes without labels and only one plot produced instead of many using matplotlib with LateX

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

Latex labels with seaborn

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.

Error setting tick positions with matplotlib in python

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).

Categories

Resources