3

I'm actually trying out the solution presented in how to annotate heatmap with text in matplotlib? . Although this actually works fine with numbers; I've been trying to do the same with unicode text and the problem is, although simple text is printed out fine, more exotic ones (like greek) are not. I've tried encoding and decoding with a bunch of codecs ('utf-8-sig','cp737','cp1252',etc) but the problem still remains. Any ideas? I'm using windows7 and python 3.3. Using the following code will reproduce the problem.

# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
fig5, ax5a = plt.subplots()
data = np.random.rand(5, 4)
heatmap = ax5a.pcolor(data,cmap=plt.cm.Blues)
commUrlCategoryHeatmap = {0: {0: 'νεα',1: 'news',2: 'νεα',3: 'news',4: 'νεα'},
                          1: {0: 'news',1: 'νεα',2: 'news',3: 'νεα',4: 'νεα'},
                          2: {0: 'news',1: 'νεα',2: 'Ειδήσεις και ΜΜΕ',3: 'νεα',4: 'news'},
                          3: {0: 'νεα',1: 'νεα',2: 'news',3: 'Periódicos',4: 'Ειδήσεις και ΜΜΕ'},
                          4: {0: 'νεα',1: 'news',2: 'νεα',3: 'news',4: 'Ειδήσεις και ΜΜΕ'}}
for y in range(data.shape[0]):
    for x in range(data.shape[1]):
        print(commUrlCategoryHeatmap[y][x].encode('utf-8').decode('utf-8-sig'))
        plt.text(x + 0.5, y + 0.5, commUrlCategoryHeatmap[y][x].encode('utf-8').decode('utf-8-sig') ,horizontalalignment='center',verticalalignment='center',fontsize = 10, rotation = 35)
plt.colorbar(heatmap)
plt.show()

1 Answer 1

4

You can place the text between $ signs to render the text with TeX, see this link for some background information: http://matplotlib.org/users/mathtext.html

Modify the line plotting the text to:

    plt.text(x + 0.5, y + 0.5, '$%s$' %  commUrlCategoryHeatmap[y][x],
             ha='center',va='center',fontsize=16, rotation=35)

And that gives me this result:

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Sir, you are a life saver. Although I'm a Tex user myself, I'd never thought of that in a hundred years!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.