Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unicode error using matplotlib with log scale on Windows

I'm using python 2.6 and matplotlib. If I run the sample histogram_demo.py provided in the matplotlib gallery page, it works fine. I've simplified this script greatly:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

fig = plt.figure()
ax = fig.add_subplot(111)

n, bins, patches = ax.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

ax.set_yscale('log')  # <---- add this line to generate the error
plt.show()

I get this error (at the plt.show() line):

TypeError: coercing to Unicode: need string or buffer, dict found

I've tried changing the backend to many different values - nothing helps. I am using Qt4Agg. Is this a font issue? It seems that it must be something with my configuration. Note: Because of other problems, I just installed a fresh copy of python26, matplotlib, numpy, scipy. I have another XP-box running python26 and it executes both versions of the script with no errors. I hope someone can help. Many thanks in advance.

like image 840
casey Avatar asked Aug 13 '10 18:08

casey


3 Answers

This is a bug in the font management of matplotlib, on my machine this is the file /usr/lib/pymodules/python2.6/matplotlib/font_manager.py:1220. I've highlighted the change in the code snippet below; this is fixed in the newest version of matplotlib.

if best_font is None or best_score >= 10.0:
    verbose.report('findfont: Could not match %s. Returning %s' %
                       (prop, self.defaultFont))
    [+]result = self.defaultFont[fontext]
    [-]result = self.defaultFont
    print "defaultFont", result
else:
    verbose.report('findfont: Matching %s to %s (%s) with score of %f' %
                       (prop, best_font.name, best_font.fname, best_score))
    result = best_font.fname
    print "best_font", result

This error occurs only if no "good" font was found and the font manager falls back to a default font. Therefore the error occured without apparent reason, probably because of changes in the installed fonts.

Hope that helps!

like image 127
Dieter Weber Avatar answered Nov 14 '22 09:11

Dieter Weber


I had the same problem with matplotlib 0.98.5.2. I was able to fix it by upgrading to matplotlib 1.0.1 (0.99.3 didn't work), or by blowing away my ~/.matplotlib directory. Not sure what the equivalent is for Windows.

like image 5
Paul Price Avatar answered Nov 14 '22 08:11

Paul Price


I had the same problem today, and I found the issue in github

https://github.com/matplotlib/matplotlib/issues/198

The proposed workaround is to delete the .matplotlib/fontList.cache file, and worked for me.

like image 1
Pablo Navarro Avatar answered Nov 14 '22 08:11

Pablo Navarro