python - 如何使用 matplotlib 用 unicode 文本注释热图?

标签 python unicode matplotlib heatmap

我实际上正在尝试 how to annotate heatmap with text in matplotlib? 中提供的解决方案.尽管这实际上对数字很有效;我一直在尝试对 unicode 文本做同样的事情,问题是,虽然简单的文本打印得很好,但更奇特的文本(如希腊语)却没有。我已经尝试使用一堆编解码器(“utf-8-sig”、“cp737”、“cp1252”等)进行编码和解码,但问题仍然存在。有任何想法吗?我正在使用 windows7 和 python 3.3。 使用以下代码将重现该问题。

# -*- 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()

最佳答案

您可以将文本放在 $ 符号之间以使用 TeX 呈现文本,请参阅此链接了解一些背景信息:http://matplotlib.org/users/mathtext.html

将绘制文本的行修改为:

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

这给了我这个结果:

enter image description here

关于python - 如何使用 matplotlib 用 unicode 文本注释热图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28853457/

相关文章:

python - 如何在python中对日期进行排序?

python - Python 中的分割线是一个带有空格的表格

unicode - Python 3是使用sys.stdout.buffer.write()好的样式吗?

python - 按日期排序 Pandas ,自定义聚合器 : combine all the data for each date

delphi - 从delphiXE使用pchar参数调用delphi 2006 dll

Python 的 string.format() 和 Unicode

python - 为什么 matplotlib 轴应该包含的 Line2D 对象显示为空?

python - 创建 matplotlib 图后如何设置布局以及可能的选择是什么?

python - matplotlib:同一张图上有2个不同的图例

python - 如何在反向传播算法中使用链式法则的结果中的矩阵相乘